Java 10 · Topic 1 of 2
var (local type inference)
Definition​
var lets the compiler work out the type of a local variable from the value on the right, so you do not repeat a long type name. The variable is still strongly typed; it is just not written out.
Example code​
Less typing, same safety
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class Demo {
public static void main(String[] args) {
var names = new ArrayList<String>(); // inferred as ArrayList<String>
names.add("Asha");
var ages = new HashMap<String, Integer>(); // inferred as HashMap<String, Integer>
ages.put("Asha", 30);
for (var entry : ages.entrySet()) { // handy for long types
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
// names = 5; // still a compile error: the type is fixed
System.out.println(names);
}
}
// Output:
// Asha -> 30
// [Asha]
Finished this page? Track your progress (saved only in your browser).