Java Variables

Java is statically typed — every variable has a declared type that never changes.

Java
String name = "Sita";
int age = 21;
double height = 5.4;
boolean isStudent = true;
char grade = 'A';

Declaration and assignment

Java
int x;        // declare
x = 10;       // assign
int y = 20;   // both at once
int a = 1, b = 2, c = 3;  // several of the same type

final

final makes a variable unchangeable after assignment — Java's constant:

Java
final double VAT_RATE = 0.13;
// VAT_RATE = 0.15;  ← compile error

Mark things final by default. It documents intent and prevents a whole class of accidental reassignment bugs.

var (Java 10+)

var infers the type from the right-hand side. The variable is still statically typed — this is not any:

Java
var name = "Sita";           // String
var count = 42;              // int
var list = new ArrayList<String>();  // ArrayList<String>

// var x;        ← error: no initialiser, nothing to infer from
// name = 42;    ← error: still a String

Use var when the type is obvious from the right side, and spell the type out when it isn't.

Scope

A variable exists only inside the { } block where it was declared:

Java
public class Main {
    static int classLevel = 1;   // visible to the whole class

    public static void main(String[] args) {
        int methodLevel = 2;     // visible in main only

        if (true) {
            int blockLevel = 3;  // visible in this if-block only
        }
        // System.out.println(blockLevel);  ← error
    }
}