Modern Java 8+ Features · Modern Java (10–21)

var: Local Type Inference

Since Java 10, let the compiler work out a local variable's type. Less typing, same strong types.

VarDemo.java

import java.util.ArrayList;
import java.util.HashMap;

public class VarDemo {
    public static void main(String[] args) {
        var count = 10;                          // the compiler works out: int
        var name = "Asha";                       // String
        var scores = new ArrayList<Integer>();   // ArrayList<Integer>
        scores.add(90);
        var lookup = new HashMap<String, Integer>();
        lookup.put(name, count);
        for (var s : scores) {
            count += s;
        }
        System.out.println(count + " " + lookup);
    }
}

Step by step

  1. var count = 10: the compiler infers int.
  2. name is created and refers to the text "Asha". Because it is a literal, Java stores it once in the string pool.
  3. Inferred as ArrayList<Integer>, without writing it twice.
  4. 90 is added to the end of the ArrayList that scores points to.
  5. lookup is created on the stack and points to a new HashMap on the heap: {}.
  6. A new key Asha with the value 10 is added to the HashMap that lookup points to.
  7. var works in for loops too: s is an Integer.
  8. count changes from 10 to 100. s goes out of scope and disappears.
  9. The end of this block is reached.
  10. Java moves to the next element of the loop: for (var s : scores).
  11. It prints 100 {Asha=10}.
  12. count 100 and {Asha=10}. Every var had a precise type, worked out by the compiler.