Variables

A variable gives a value a name. Its declaration tells Java the value's type, the name you will use, and optionally its starting value.

Java is statically typed. Once score is declared as an int, the compiler prevents you from assigning text to it. That check happens before the program runs.

A value that can change

public class Main {
    public static void main(String[] args) {
        String book = "Dune";
        int page = 120;

        System.out.println(book);
        System.out.println(page);

        page = 145;
        System.out.println(page);
    }
}

Output:

Dune
120
145

book holds text, while page holds a whole number. The second assignment changes the value in page; it does not declare a new variable, so the type is not written again.

A local variable must receive a value before it is read. Java reports an uninitialized local variable as a compile error.

Choose the right variable types for a small product summary.