Back to Study Material Java

Java Data Types

Java has a two-tier type system: primitive types and reference types. Primitive types are the most basic data types built into the language. They hold simp...

Java Data Types

Primitive and Reference Types in Java

Java has a two-tier type system: primitive types and reference types. Primitive types are the most basic data types built into the language. They hold simple values directly and are stored on the stack (or inline within objects on the heap). Reference types include classes, interfaces, arrays, and enumerations; variables of reference types store addresses pointing to objects on the heap rather than the objects themselves.

Java defines exactly eight primitive types. byte is an 8-bit signed integer with a range from -128 to 127. short is a 16-bit signed integer ranging from -32,768 to 32,767. int is a 32-bit signed integer, the default type for whole numbers, ranging from about -2.1 billion to 2.1 billion. long is a 64-bit signed integer for very large whole numbers and must be declared with an L suffix: long population = 8000000000L;. float is a 32-bit IEEE 754 floating-point number and must use an F suffix: float pi = 3.14F;. double is a 64-bit floating-point number and is the default type for decimal literals. char is a 16-bit unsigned integer representing a single Unicode character, written in single quotes: char grade = 'A';. boolean represents a true/false value and is the only type that cannot be cast to or from numeric types in Java.

String is not a primitive type; it is a class in the java.lang package. String objects are immutable — once created, their content cannot be changed. String literals are interned by the JVM, meaning that two string literals with the same content may refer to the same object in the string pool.

Choosing the right type matters for performance and correctness. Using int for a counter is fine; using byte when values could exceed 127 causes overflow and produces wrong results silently. For financial calculations, neither float nor double is appropriate because binary floating-point cannot represent all decimal fractions exactly; use java.math.BigDecimal instead.

Literal values can be written in different bases: 0x prefix for hexadecimal (0xFF), 0b prefix for binary (0b1010). Underscores can be used as digit separators in numeric literals for readability: int million = 1_000_000;.

Interview tip: A favorite exam question is "what is the default value of a local variable in Java?" The answer is that local variables have no default value and must be explicitly initialized before use. Instance variables, however, do receive defaults: 0 for numeric types, '' for char, false for boolean, and null for reference types.