Java Data Types
A data type is the kind of value a variable can hold in Java. The primitive types are the basic kinds for numbers, truth values, and single characters.
One variable of each numeric type
Each line declares one numeric type. The print lines show all six values in order.
public class Main {
public static void main(String[] args) {
byte small = 100;
short medium = 3000;
int count = 50000;
long big = 9000000000L;
float price = 5.5f;
double rate = 19.99;
System.out.println(small);
System.out.println(medium);
System.out.println(count);
System.out.println(big);
System.out.println(price);
System.out.println(rate);
}
}A float without the f is refused
The value 5.5 is a double by default. A float variable cannot take it without the letter f.
public class Main {
public static void main(String[] args) {
float temperature = 5.5;
System.out.println(temperature);
}
}The type shapes the printed form
The int variable holds the whole value 5. The double variable holds 5.0 and prints with its decimal part.
public class Main {
public static void main(String[] args) {
int whole = 5;
double decimal = 5.0;
System.out.println(whole);
System.out.println(decimal);
}
}Example
public class Main {
public static void main(String[] args) {
int pages = 320;
long copies = 1200000L;
float rating = 4.5f;
double weight = 0.75;
System.out.println(pages);
System.out.println(copies);
System.out.println(rating);
System.out.println(weight);
}
}Key points
- Java has eight primitive types.
- byte, short, int, and long hold whole numbers of growing size.
- float and double hold decimal numbers.
- double is the wider decimal type.
- A float value needs the letter f after its number.
- boolean holds true or false, and its code arrives in the Booleans lesson.
- char holds one character, and its code arrives in the Characters lesson.
In this example, a book is described with four numeric types. The int and long variables hold whole counts. The float and double variables hold decimal measures. Each print line shows the value in the form of its type.
Note
String is not a primitive type.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
The primitive types
| Type | Size | Example |
|---|---|---|
| byte | 1 byte | 100 |
| short | 2 bytes | 5000 |
| int | 4 bytes | 100000 |
| long | 8 bytes | 15000000000L |
| float | 4 bytes | 5.75f |
| double | 8 bytes | 19.99 |
| boolean | 1 bit | true |
| char | 2 bytes | 'B' |
Exercise
Which letter must follow a decimal value stored in a float variable?