The var Keyword

Local Type Inference

Since Java 10 you can write var for local variables. The compiler works out the type from the value. The variable is still strongly typed.

Example

public class Main {
    public static void main(String[] args) {
        var count = 10;           // int
        var price = 99.99;        // double
        var city = "Bengaluru";   // String
        var active = true;        // boolean
        System.out.println(count + 1);
        System.out.println(price * 2);
        System.out.println(city.toUpperCase());
        System.out.println(!active);
        // count = "ten";  // error: incompatible types, count is an int
    }
}

Output

11
199.98
BENGALURU
false

Rules for var

  • Only for local variables inside methods (and loop variables), not for fields or method parameters.
  • Must be initialised on the same line: var x; is an error.
  • Cannot be initialised with null alone.
  • Use it when the type is obvious from the right side; write the type when it improves readability.