Sub topic 2
Declaring Variables with `var`
This chapter assumes you know basic Java local variables, primitive and reference types, and how constructors create objects. It also assumes Java 10 or later. Java added local variable type inference in Java 10.
The var declaration lets the compiler determine a local variable's type from its initializer. An initializer is the expression that gives the variable its first value.
The basic form is:
var variableName = initializer;For example:
public class VarBasics {
public static void main(String[] args) {
var count = 10;
var name = "Ada";
System.out.println(count);
System.out.println(name);
}
}The compiler infers int for count and String for name. After compilation, these variables still have fixed static types. Static typing means that Java checks the type of every operation at compile time.
var count = 10;
// count = "ten"; // Does not compile: count is an intvar does not make Java dynamically typed. It only removes the repeated type name from a local declaration.
What the Compiler Infers
The compiler examines the initializer and assigns the variable the initializer's type.
var numbers = new java.util.ArrayList<Integer>();
numbers.add(10);
// numbers.add("ten"); // Does not compileHere, numbers has the static type ArrayList<Integer>. The compiler knows that its elements must be Integer values.
The difference from an explicit declaration is mostly visual:
| Explicit declaration | Declaration with `var` |
|---|---|
| `String message = "Hello";` | `var message = "Hello";` |
| `ArrayList<Integer> values = new ArrayList<>();` | `var values = new ArrayList<Integer>();` |
| `int total = 42;` | `var total = 42;` |
With var, the initializer is required because it provides the information needed for inference.
Where `var` Can Be Used
var is intended for local variables inside methods, constructors, and initializer blocks. It can also declare variables controlled by both forms of for loop.
import java.util.List;
public class VarContexts {
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 enhanced for loop, word is inferred as String. In the basic for loop, index is inferred as int.
var also works for a resource in a try-with-resources statement:
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("hello"))) {
System.out.println(reader.readLine());
}
}
}The compiler infers BufferedReader for reader, so methods such as readLine() are available.
> callout note > var is a local variable feature. It cannot declare fields, method parameters, or method return types. Those parts of a class still need explicit types.
One Variable and One Initializer
A var declaration must have one variable name and an initializer whose type the compiler can determine.
public class VarRequiredInitializer {
public static void main(String[] args) {
// var missing; // No initializer
// var unknown = null; // null has no usable type
// var first = 1, second = 2; // Multiple declarators
var values = new int[] {1, 2, 3};
System.out.println(values.length);
}
}An array initializer by itself also lacks a type:
// var values = {1, 2, 3}; // Does not compileThe array creation expression supplies the missing type information in new int[] {1, 2, 3}.
Exercise
What static type does Java infer for var title = "Java";, and why can the variable not later hold an integer?
Show answer
Java infers String from the string initializer. The variable keeps that fixed static type, so assigning an integer violates the compile-time type check.