Careeroza
Primitive Data Types
Two Families of Types
- Primitive types (8 of them): store the actual value directly.
byte,short,int,long,float,double,char,boolean. - Reference types: store a reference (address) to an object.
String, arrays, classes, interfaces.
The Eight Primitives
| Type | Size | Range / values | Default (fields) |
|---|---|---|---|
byte | 1 byte | -128 to 127 | 0 |
short | 2 bytes | -32,768 to 32,767 | 0 |
int | 4 bytes | about -2.1 billion to 2.1 billion | 0 |
long | 8 bytes | about -9.2 x 10^18 to 9.2 x 10^18 | 0L |
float | 4 bytes | ~6-7 decimal digits precision | 0.0f |
double | 8 bytes | ~15-16 decimal digits precision | 0.0 |
char | 2 bytes | one Unicode character (0 to 65,535) | '\u0000' |
boolean | - | true or false | false |
All Primitives in Action
Example
public class Main {
public static void main(String[] args) {
byte level = 5;
short year = 2025;
int population = 1_400_000_000; // underscores make big numbers readable
long distanceToSunKm = 149_600_000L;
float rating = 4.5f;
double pi = 3.141592653589793;
char grade = 'A';
boolean isOpen = true;
System.out.println(level + " " + year + " " + population);
System.out.println(distanceToSunKm + " " + rating + " " + pi);
System.out.println(grade + " " + isOpen);
}
}Output
5 2025 1400000000 149600000 4.5 3.141592653589793 A true
Tip: Use int for whole numbers and double for decimals unless you have a reason not to. Add L for long literals and f for float literals.