Declaring Variables

What is a Variable?

A variable is a named box in memory that stores a value. In Java every variable has a type that decides what it can hold.

type variableName = value;
TypeStoresExample
intwhole numbersint age = 21;
doubledecimal numbersdouble price = 99.5;
charone characterchar grade = 'A';
booleantrue / falseboolean isPaid = true;
StringtextString city = "Chennai";

Declare, Assign, Change

Example

You can declare a variable first and assign it later. Assigning again replaces the old value.

public class Main {
    public static void main(String[] args) {
        int score;          // declare
        score = 50;         // assign
        System.out.println("Score: " + score);
        score = 75;         // change (overwrite)
        System.out.println("Score: " + score);

        String name = "Priya";  // declare + assign together
        double height = 5.4;
        boolean isStudent = true;
        System.out.println(name + " " + height + " " + isStudent);
    }
}

Output

Score: 50
Score: 75
Priya 5.4 true

Multiple Variables

Example

Declare several variables of the same type on one line, or give many variables the same value.

public class Main {
    public static void main(String[] args) {
        int x = 5, y = 6, z = 50;
        System.out.println(x + y + z);

        int a, b, c;
        a = b = c = 10;
        System.out.println(a + " " + b + " " + c);
    }
}

Output

61
10 10 10

Note: A local variable must be assigned before it is used. int n; System.out.println(n); gives the compile error variable n might not have been initialized.