The types you'll use most
| Type | Holds | Example |
|---|---|---|
int | whole numbers | int apples = 12; |
double | decimal numbers | double price = 45.5; |
boolean | true or false | boolean isOpen = true; |
char | one single character | char grade = 'A'; |
String | text (many characters) | String name = "Ravi"; |
public class Main {
public static void main(String[] args) {
int apples = 12;
double price = 45.5;
boolean isOpen = true;
char grade = 'A';
String shop = "Fresh Fruits";
System.out.println(shop + " is open: " + isOpen);
System.out.println(apples + " apples cost " + (apples * price));
System.out.println("Grade: " + grade);
}
}Output
Fresh Fruits is open: true 12 apples cost 546.0 Grade: A
Common mistake: A
charuses single quotes ('A'). AStringuses double quotes ("A"). Mixing them up is a compile error.
Primitive types
int, double, boolean and char are primitive types: simple values built into Java, written in lowercase. String is different – it is a class (that's why it has a capital S). You'll learn about classes later.
Java has 8 primitive types in total. The others are for special sizes:
| Type | Size | Used for |
|---|---|---|
byte | very small | whole numbers from -128 to 127 |
short | small | whole numbers from -32,768 to 32,767 |
int | normal | whole numbers up to about 2 billion |
long | big | really huge whole numbers |
float | normal | decimals (less exact than double) |
double | big | decimals – the usual choice |
boolean | - | true / false |
char | - | one character |
When int is too small
An int can't go past about 2.1 billion. For bigger numbers use long and put an L at the end of the number:
public class Main {
public static void main(String[] args) {
int biggestInt = 2147483647;
long worldPopulation = 8100000000L;
System.out.println(biggestInt);
System.out.println(worldPopulation);
}
}Output
2147483647 8100000000
Tip: You can use underscores to make big numbers readable:
8_100_000_000L. Java ignores them.