Using var for Locals
Let the compiler infer the type.
Local Type Inference
Since Java 10, you can declare local variables with var and let the compiler infer the type from the initializer. This is local type inference. The variable is still strongly typed.
Your First var
Replace an explicit type with var when assigning a value. The compiler sees the literal and infers the right type.
public class Main {
public static void main(String[] args) {
var message = "Hello";
var count = 42;
System.out.println(message + " " + count);
}
}All lessons in this course
- Using var for Locals
- When var Helps Readability
- var in for Loops
- Limitations of var