Java Tutorial · Java Basics · Lesson 7 of 37

Java Data Types

The eight primitive types, wrapper classes and reference types.

Primitive types

Type Size Example
byte 8 bits 100
short 16 bits 30000
int 32 bits 2_000_000
long 64 bits 9_000_000_000L
float 32 bits 3.14f
double 64 bits 3.14159
boolean — true
char 16 bits 'A'

Use int for whole numbers, long for very large ones (IDs, timestamps), and double for decimals. Underscores make long literals readable.

Example 1
public class Main {
    public static void main(String[] args) {
        int population = 8_100_000;
        long distanceKm = 384_400L;
        double pi = 3.14159;
        char letter = 'J';
        boolean ready = true;
        System.out.println(population + " " + distanceKm + " " + pi + " " + letter + " " + ready);
        System.out.println("int range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
        System.out.println(Integer.MAX_VALUE + 1);  // overflow wraps around!
    }
}

Output

8100000 384400 3.14159 J true
int range: -2147483648 to 2147483647
-2147483648

Run this on your computer — see “Get Started” for setup.

Reference types and wrappers

Everything else — String, arrays, your own classes — is a reference type: the variable holds a reference to an object, which can be null. Each primitive has a wrapper class (Integer, Double, Boolean…) used in collections. Java converts between them automatically (autoboxing).

Example 2
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);            // autoboxing int -> Integer
        int first = numbers.get(0); // unboxing Integer -> int
        Integer a = 1000, b = 1000;
        System.out.println(first + " " + (a == b) + " " + a.equals(b));
    }
}

Output

5 false true

Run this on your computer — see “Get Started” for setup.

Comparing wrapper objects with == compares references, not values — always use equals(). See the Integer cache puzzle.

Test yourself

Which type should you use for a whole number larger than about 2.1 billion?

  1. int
  2. short
  3. long
  4. float
Show answer

Answer: long

Practice next