Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

var

Declares a local variable whose type the compiler infers from the value.

Available since: Java 10

Syntax

var name = value;

Examples

The type comes from the right-hand side:

void main() {
    var count = 10;
    var name = "Anna";
    var prices = new ArrayList<Double>();
    prices.add(9.99);
    IO.println(count + " " + name + " " + prices);
}

Output:

10 Anna [9.99]

The type is inferred once and does not change later:

void main() {
    var total = 0;
    total += 5;
    // total = "five";  // error: incompatible types: String cannot be converted to int
    IO.println(total);
}

Output:

5

Notes

var is not dynamic typing: the variable gets a concrete type at compile time. It can only be used for local variables with an initial value and in for loops; not for fields, parameters or return types. var x; and var x = null; do not compile.

var helps when the type is already visible on the right (new ArrayList<String>()) and hurts when the right side is a method call with a non-obvious result.

See also

  • final — Forbids reassigning a variable, overriding a method or extending a class.
  • new — Creates a new object or array and calls the constructor.

In the tutorial

  • Variables — Declaring variables in Java: type and name, assignment, var, final constants and naming rules.

Thanks for reading!

Donate to the site — we work hard for you.