W3docs

Java Variables

Declare and initialize variables in Java, understand variable types (local, instance, static), and follow Java naming conventions.

A variable is a named storage location with a fixed type. Once declared, the type can't change, but the value inside it usually can. The type controls how much memory the variable uses, which values are legal, and which operations the compiler allows. This chapter covers how to declare variables, how to initialize them, the four kinds Java distinguishes, and the rules around final, var, and scope.

Declaring a variable

The basic form is a type followed by a name and a semicolon:

type name;

For example, int score; reserves an int-shaped slot named score. The type is one of Java's built-in types (int, double, boolean, char, …) or any class or interface — see Java Data Types for the full list.

The simplest declarations:

int score;
String name;
boolean ready;

These reserve storage; they don't put a value in it yet.

Initializing

To assign a value, use =:

int score = 0;
String name = "Ada";
boolean ready = true;

You can also declare and assign separately:

int score;
score = 0;

Or declare several variables of the same type at once:

int x = 1, y = 2, z = 3;

(One-per-line is usually clearer.)

Local variables must be assigned before use

A local variable — declared inside a method — has no default value. The compiler refuses to let you read it until you've assigned something:

public static void main(String[] args) {
    int x;
    // System.out.println(x); // compile error: variable x might not have been initialized
    x = 5;
    System.out.println(x);    // OK
}

This is one of Java's most useful safety features — it catches a category of bugs other languages let slip through.

The four kinds of variables

Java distinguishes four variable categories by where they're declared:

  1. Local variables — declared inside a method or block. Live only while the method runs. No default value. Must be initialised before use.
  2. Instance variables (fields) — declared inside a class but outside any method. One copy per object. Default to 0 / 0.0 / false / null.
  3. Static variables (class variables) — declared with the static keyword. One copy shared by every instance of the class. Default to 0 / false / null.
  4. Parameters — declared in a method signature; receive the value passed by the caller.
public class Counter {
    static int totalCounters;   // static (class) variable
    int count;                  // instance variable

    public void add(int delta) { // delta is a parameter
        int doubled = delta * 2; // doubled is a local variable
        count += doubled;
    }
}

You'll meet instance and static variables again in the OOP chapters; for now most of the variables you write will be local.

final — assign once

Prefixing a declaration with final makes the variable a one-shot binding. After the first assignment, it cannot change:

final int MAX_RETRIES = 3;
// MAX_RETRIES = 4; // compile error: cannot assign a value to final variable

Using final for things that aren't supposed to change makes intent explicit and lets the compiler catch accidental reassignment. By convention, final fields that hold fixed constants are named in UPPER_SNAKE_CASE (see Java Naming Conventions).

Note that final freezes the binding, not the object it points to. A final reference can't be reassigned, but the object it refers to can still be mutated:

final int[] nums = {1, 2, 3};
nums[0] = 99;        // OK — the array contents change
// nums = new int[5]; // compile error — the reference is final

var — let the compiler pick the type

Since Java 10, you can write var instead of a type for local variables when the right-hand side makes the type obvious:

var name = "Ada";          // inferred as String
var score = 0;             // inferred as int
var values = new int[10];  // inferred as int[]

var is not dynamic typing — the variable still has a fixed type, the compiler just figures it out for you. Restrictions:

  • Only for local variables.
  • The right-hand side must be present (var x; is illegal).
  • Not allowed for parameters, instance variables, or static variables.

var is most helpful when the type name is long or obvious from context:

var orders = new HashMap<String, List<Order>>();

Use ordinary type declarations when the inferred type isn't obvious to a reader.

Scope

A variable is in scope — visible — from its declaration to the end of the enclosing block:

public static void main(String[] args) {
    int outer = 1;

    if (outer > 0) {
        int inner = 2;
        System.out.println(outer + inner);   // both visible
    }

    // System.out.println(inner);   // compile error: inner is out of scope
}

You cannot declare two local variables with the same name in overlapping scopes — but a name can be reused in two separate, non-overlapping blocks:

for (int i = 0; i < 3; i++) { /* i lives here */ }
for (int i = 0; i < 5; i++) { /* a new, separate i */ }  // fine

Keeping variable scopes small is good practice: declare each variable as close as possible to where it's first used.

A working example

java— editable, runs on the server

What's next

Java Naming Conventions covers the standard rules every Java codebase follows for class, method, variable, and constant names.

Practice

Practice
Which statement about Java variables is correct?
Which statement about Java variables is correct?
Was this page helpful?