Sub topic 4
Where You Can Use `var`
This chapter assumes you know basic Java declarations, primitive and reference types, generics, enhanced for loops, try-with-resources, and lambda expressions. Java's var feature is local variable type inference. It lets the compiler determine a local variable's type from its initializer.
You can use var only where Java has enough information to infer one fixed type. The variable remains statically typed after compilation.
Ordinary Local Variables
The most common use is a local variable inside a method. The declaration must include an initializer.
import java.util.ArrayList;
import java.util.HashMap;
public class VarBasics {
public static void main(String[] args) {
var count = 10; // int
var name = "Ada"; // String
var scores = new ArrayList<Integer>(); // ArrayList<Integer>
scores.add(count);
var byName = new HashMap<String, Integer>();
byName.put(name, scores.get(0));
System.out.println(byName); // {Ada=10}
}
}The compiler infers count as int, name as String, and scores as ArrayList<Integer>. Later assignments and method calls are checked using those types:
var count = 10;
// count = "ten"; // Does not compileA var declaration cannot be a field, method parameter, or method return type. It is designed for local declarations whose initializer is visible at the declaration site.
Loop Variables
You can use var in both common kinds of for loop.
An enhanced for loop uses var for each element:
import java.util.List;
public class VarLoops {
public static void main(String[] args) {
var words = List.of("alpha", "beta", "gamma");
for (var word : words) {
System.out.println(word.toUpperCase());
}
for (var index = 0; index < words.size(); index++) {
System.out.println(index + ": " + words.get(index));
}
}
}In the first loop, word is inferred as String. In the second loop, index is inferred as int. The loop variable is still checked at compile time.
Try-With-Resources
A try-with-resources statement can use var when it creates a resource. A resource is an object that Java closes automatically, such as a reader or input stream.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class VarResource {
public static void main(String[] args) throws IOException {
try (var reader =
new BufferedReader(new StringReader("first line\nsecond line"))) {
System.out.println(reader.readLine());
}
}
}Here, reader is inferred as BufferedReader. When execution leaves the try block, Java closes it automatically.
A Declaration Must Have an Initializer
The compiler cannot infer a type when no value appears on the right side.
public class VarRequired {
public static void main(String[] args) {
// var missing; // No initializer
// var nothing = null; // null has no usable type
// var values = {1, 2, 3}; // Array initializer needs a declared type
var values = new int[] {1, 2, 3};
System.out.println(values.length);
}
}A lambda expression and a method reference also need a target type. Since var is asking the compiler to infer the type, these forms cannot stand alone in a local var declaration. Lambda parameters have a separate rule discussed later.
Where `var` Is Allowed
Practice
Exercise
In for (var item : List.of("red", "blue")), what is the inferred type of item, and why?
Show answer
item is inferred as String because each element produced by the list has type String.