Sub topic 1
Starting point: explicit types in Java
Prerequisites
This chapter assumes basic Java syntax, local variables, primitive and reference types, and simple generic types. You should also recognize enhanced for loops and object construction. The examples require Java 10 or later.
Explicit types make the static type visible
Java is statically typed. A variable's type is checked by the compiler before the program runs. In an explicit declaration, you write the type before the variable name:
String name = "Ada";
int score = 10;name has type String, and score has type int. The compiler rejects operations that do not match those types:
// score.toUpperCase(); // compile-time error: int has no such methodExplicit types also communicate the abstraction you want to expose:
List<String> names = new ArrayList<>();The variable can use the List interface even though the object is an ArrayList.
Declaring variables with `var`
var asks the compiler to infer a local variable's type from its initializer:
import java.util.ArrayList;
public class VarExample {
public static void main(String[] args) {
var name = "Ada"; // String
var score = 10; // int
var names = new ArrayList<String>(); // ArrayList<String>
names.add(name);
System.out.println(names + ": " + score);
}
}Inference does not make Java dynamically typed. Each variable receives one fixed static type. Later assignments and method calls are checked against that type.
How the compiler infers the type
The initializer must provide enough information for one unambiguous type. The compiler infers int for 10, String for "Ada", and ArrayList<String> for new ArrayList<String>().
The distinction between an inferred type and an explicit interface type matters:
var list = new ArrayList<String>(); // ArrayList<String>
List<String> other = new ArrayList<>(); // List<String>The first variable can call ArrayList-specific methods. The second can use only methods declared by List.
Where you can use `var`
You can use var for ordinary local variables, enhanced for variables, basic for variables, and try-with-resources variables:
for (var item : names) {
System.out.println(item);
}
try (var reader = new java.io.StringReader("text")) {
System.out.println(reader.read());
}It is not used for fields, method parameters, or return types. It also requires an initializer, so var value; cannot compile.
Exercise
What static type does var count = 10; have, and when is that type determined?
Show answer
It has type int, determined by the compiler at compile time from the initializer.