Java Tutorial · Java Basics · Lesson 6 of 37

Java Variables

Declare typed variables, use var, final constants and naming rules.

Declaring variables

Java is statically typed: every variable has a type that's fixed when you declare it.

Example 1
public class Main {
    public static void main(String[] args) {
        String name = "Ada";
        int age = 36;
        double height = 1.68;
        boolean isAdmin = true;
        char grade = 'A';
        age = age + 1;
        System.out.println(name + " is " + age + ", grade " + grade + ", admin: " + isAdmin);
    }
}

Output

Ada is 37, grade A, admin: true

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

var — local type inference

Since Java 10, var lets the compiler infer the type of a local variable from its initial value. The variable is still statically typed:

Example 2
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        var city = "London";        // String
        var count = 10;              // int
        var prices = new ArrayList<Double>();
        prices.add(9.99);
        System.out.println(city + " " + count + " " + prices);
    }
}

Output

London 10 [9.99]

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

final — constants

A final variable can be assigned only once. Class-level constants are usually static final with UPPER_SNAKE_CASE names.

Example 3
public class Main {
    public static void main(String[] args) {
        final int maxUsers = 100;
        // maxUsers = 200;  // compile error: cannot assign a value to final variable
        System.out.println("Max users: " + maxUsers + ", tax: " + TAX_RATE);
    }

    static final double TAX_RATE = 0.2;
}

Output

Max users: 100, tax: 0.2

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

Test yourself

Which keyword makes a variable impossible to reassign?

  1. const
  2. static
  3. final
  4. var
Show answer

Answer: final