Java Data Types
In this page:
Primitive Data Types
Java splits its type system into 8 primitives (byte, short, int, long, float, double, char, boolean) baked directly into the language, versus reference types like String or arrays that point to objects on the heap.
Example: Primitive Data Types
public class Main {
public static void main(String[] args) {
int number = 5; // primitive
String text = "Hi"; // reference type - points to an object on the heap
System.out.println(number + " " + text);
}
}
Login to try C/C++/Java/PHP code in the editor
Numeric Types
Choosing the right numeric size matters for memory and correctness: an int can hold about +-2.1 billion, so counting something that could exceed that (like a national population) needs a long instead.
Example: Numeric Types
public class Main {
public static void main(String[] args) {
int population = 2_100_000_000; // near int's ~2.1 billion limit
long worldPopulation = 8_000_000_000L; // needs long - exceeds int's range
System.out.println(population + " " + worldPopulation);
}
}
Login to try C/C++/Java/PHP code in the editor
Floating-Point Types
float and double both store fractional values using IEEE 754 floating-point representation, but double's extra bytes give it roughly twice the significant digits of precision, which is why it's the default choice for most decimal math in Java.
Example: Floating-Point Types
public class Main {
public static void main(String[] args) {
float f = 3.14f;
double d = 3.14159265358979; // double holds roughly twice the significant digits
System.out.println(f + " " + d);
}
}
Login to try C/C++/Java/PHP code in the editor
Character and Boolean Types
char stores exactly one 16-bit Unicode character in single quotes like A, while boolean can only ever hold true or false -- unlike C, Java never lets you treat an int as a boolean or vice versa.
Example: Character and Boolean Types
public class Main {
public static void main(String[] args) {
char grade = 'A';
boolean passed = true;
System.out.println(grade + " " + passed);
}
}
Login to try C/C++/Java/PHP code in the editor
Reference Data Types
String and arrays are reference types: the variable itself holds a memory address pointing to the actual object on the heap, which is why comparing two Strings with == compares addresses, not their text content.
Example: Reference Data Types
public class Main {
public static void main(String[] args) {
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false - compares memory addresses
System.out.println(a.equals(b)); // true - compares actual text content
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: