Modern Java 8+ Features · Modern Java (10–21)
Since Java 10, let the compiler work out a local variable's type. Less typing, same strong types.
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);
}
}name is created and refers to the text "Asha". Because it is a literal, Java stores it once in the string pool.scores points to.lookup is created on the stack and points to a new HashMap on the heap: {}.Asha with the value 10 is added to the HashMap that lookup points to.count changes from 10 to 100. s goes out of scope and disappears.for (var s : scores).100 {Asha=10}.