Primitive types
Java has eight primitive types — the simplest types, whose values are stored directly in the variable. All other data is built from them. The type determines how much memory a value takes and which numbers fit into it.
Whole numbers
There are four whole-number types of different sizes. int is used most often, and long for very large values:
| Type | Size | Range |
|---|---|---|
byte | 1 byte | −128 to 127 |
short | 2 bytes | −32,768 to 32,767 |
int | 4 bytes | about ±2.1 billion |
long | 8 bytes | about ±9.2 × 10¹⁸ |
void main() {
int population = 146_000_000;
long distance = 9_460_730_472_580L;
IO.println(population);
IO.println(distance);
}Output:
146000000
9460730472580Underscores make a number easier to read and change nothing. The L at the end says the number is a long.
Fractional numbers
Numbers with a fractional part use double or float. Usually you pick double: it is more precise. A float value is marked with the letter f:
void main() {
double pi = 3.14159;
float rate = 0.5f;
IO.println(pi * 2);
IO.println(rate);
}Output:
6.28318
0.5Characters
The char type holds a single character. It is written in single quotes, unlike a string in double quotes:
void main() {
char grade = 'A';
char letter = 'Ж';
IO.println(grade);
IO.println(letter);
}Output:
A
Жchar covers any Unicode character, not just Latin letters.
The boolean type
The boolean type has only two values: true and false. Such values come from comparisons and control conditions:
void main() {
boolean isAdult = 20 >= 18;
IO.println(isAdult);
}Output:
trueOverflow
If a result does not fit into the type, it "wraps around" to the other end of the range. Java does not report an error:
void main() {
int max = Integer.MAX_VALUE;
IO.println(max);
IO.println(max + 1);
}Output:
2147483647
-2147483648Integer.MAX_VALUE is the largest int value. If your numbers can get that large, use long.
Common mistake
A whole number written in code is an int by default. If it is outside the int range, the program does not compile — even when the variable is a long:
void main() {
long big = 3000000000;
IO.println(big);
}Output:
Main.java:2: error: integer number too large
long big = 3000000000;
^
1 error
error: compilation failedAdd the letter L: 3000000000L.