Java's Basic Data Types

The types you'll use most

TypeHoldsExample
intwhole numbersint apples = 12;
doubledecimal numbersdouble price = 45.5;
booleantrue or falseboolean isOpen = true;
charone single characterchar grade = 'A';
Stringtext (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 char uses single quotes ('A'). A String uses 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:

TypeSizeUsed for
bytevery smallwhole numbers from -128 to 127
shortsmallwhole numbers from -32,768 to 32,767
intnormalwhole numbers up to about 2 billion
longbigreally huge whole numbers
floatnormaldecimals (less exact than double)
doublebigdecimals – 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.

HOME LABS COMMUNITY DASHBOARD