TExcelTAD
Home › Java › Java Variables

Java Variables

A variable is a named box that stores a value. In Java every variable has a type that decides what kind of value fits in the box, and that type can never change after the variable is declared.

Declaring a variable

The pattern is type name = value;

java · try it yourself
class Main {
    public static void main(String[] args) {
        String city = "Lisbon";
        int population = 545000;
        double area = 100.05;
        char grade = 'A';
        boolean isCapital = true;

        System.out.println(city);
        System.out.println(population);
        System.out.println(area);
        System.out.println(grade);
        System.out.println(isCapital);
    }
}
Lisbon
545000
100.05
A
true

The most common types for beginners:

Type Stores Example
int whole numbers int age = 30;
double decimal numbers double price = 9.99;
char a single character, in single quotes char initial = 'J';
boolean true or false boolean done = false;
String text, in double quotes String name = "Ada";

Declare first, assign later

You can create a variable without a value and assign it afterwards. You can also overwrite a value at any time — but the new value must have the same type:

java · try it yourself
class Main {
    public static void main(String[] args) {
        int score;
        score = 10;
        System.out.println("Start: " + score);
        score = 25;          // overwrite
        score = score + 5;   // use the old value to compute a new one
        System.out.println("Now: " + score);
    }
}
Start: 10
Now: 30

Note: Java won't let you read a local variable before it has been assigned. int x; System.out.println(x); is a compile error.

Constants with final

Add final when a value must never change. Trying to reassign it is a compile error. By convention, constants are written in UPPER_SNAKE_CASE:

java
final int DAYS_PER_WEEK = 7;
DAYS_PER_WEEK = 8;   // error: cannot assign a value to final variable DAYS_PER_WEEK

Combining variables

The + operator adds numbers and joins (concatenates) strings:

java · try it yourself
class Main {
    public static void main(String[] args) {
        String first = "Grace";
        String last = "Hopper";
        String full = first + " " + last;

        int x = 6, y = 7;          // several variables of one type
        int a, b, c;
        a = b = c = 1;             // same value for all three

        System.out.println(full);
        System.out.println("x * y = " + (x * y));
        System.out.println(a + b + c);
    }
}
Grace Hopper
x * y = 42
3

Type inference with var

Since Java 10 you can write var for local variables and let the compiler infer the type from the value. The variable is still statically typed — var is only a shortcut for writing:

java · try it yourself
class Main {
    public static void main(String[] args) {
        var count = 3;            // int
        var message = "hello";    // String
        var ratio = 0.75;         // double
        System.out.println(count + " " + message + " " + ratio);
        // count = "three";       // would not compile: count is an int
    }
}
3 hello 0.75

var needs an initial value, and it cannot be used for fields or method parameters.

Naming rules

Rule Valid Invalid
Letters, digits, _ and $ only total_2, $cost total-2, my name
Must not start with a digit item1 1item
Case-sensitive age ≠ Age
No reserved words classCount class, int, new

Convention: use camelCase (totalPrice, isLoggedIn) and pick descriptive names. secondsElapsed is far better than s.

Test yourself

Which declaration is valid Java?

  1. int 2nd = 5;
  2. int second = 5;
  3. int second = "5";
  4. second int = 5;

What happens if you try to reassign a final variable?

  1. The new value is ignored
  2. A runtime exception occurs
  3. The program does not compile
  4. The variable becomes non-final

In var total = 10; what is the type of total?

  1. var
  2. Object
  3. int
  4. It has no type