๐ข Data Types in Java
Java is a strongly typed language, meaning each variable must be declared with a specific data type. Java supports two main categories of data types: primitive and reference types.
๐ท๏ธ Primitive Data Types
Java has eight primitive data types, each with a specific size and value range:
- byte โ 1 byte, range: -128 to 127
- short โ 2 bytes, range: -32,768 to 32,767
- int โ 4 bytes, range: -2^31 to 2^31-1
- long โ 8 bytes, range: -2^63 to 2^63-1
- float โ 4 bytes, single-precision floating point
- double โ 8 bytes, double-precision floating point
- char โ 2 bytes, represents a single character
- boolean โ 1 bit, either
true
orfalse
๐งฑ Reference Data Types
Reference types are objects, arrays, or any other instance of a class. They do not hold the actual data but refer to the memory location where the data is stored.
- String โ Sequence of characters (reference type, not primitive).
- Arrays โ Reference type that holds a fixed number of elements of a specified type.
๐งช Example
public class DataTypesExample {
public static void main(String[] args) {
int x = 5; // primitive data type
String message = "Hi"; // reference data type
System.out.println("Integer: " + x);
System.out.println("String: " + message);
}
}