Java 10 Feature Spotlight: Mastering Local Variable Type Inference
JEP 286 − Local Variable Type Inference
Local Variable Type Inference is one of the most evident change to language available from Java 10 onwards. It allows to define a variable using var and without specifying the type of it. The compiler infers the type of the variable using the value provided. This type inference is restricted to local variables.
Old way of declaring local variable.
String name = "Welcome to tutorialspoint.com";
New Way of declaring local variable.
var name = "Welcome to tutorialspoint.com";
Now compiler infers the type of name variable as String by inspecting the value provided.
Noteworthy points
No type inference in case of member variable, method parameters, return values.
Local variable should be initialized at time of declaration otherwise compiler will not be infer and will throw error.
Local variable inference is available inside initialization block of loop statements.
No runtime overhead. As compiler infers the type based on value provided, there is no performance loss.
No dynamic type change. Once type of local variable is inferred it cannot be changed.
Complex boilerplate code can be reduced using local variable type inference.
Map<Integer, String> mapNames = new HashMap<>(); var mapNames1 = new HashMap<Integer, String>();
Example
Following Program shows the use of Local Variable Type Inference in JAVA 10.
import java.util.List;
public class Tester {
public static void main(String[] args) {
var names = List.of("Julie", "Robert", "Chris", "Joseph");
for (var name : names) {
System.out.println(name);
}
System.out.println("");
for (var i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
}
Output
It will print the following output.
Julie Robert Chris Joseph Julie Robert Chris Joseph
Java
- Java Primitive Data Types: A Complete Guide with Examples
- Master Java Operators: Types, Syntax, & Practical Examples
- Mastering Java Type Casting: From Widening to Narrowing and Beyond
- Java Variables and Data Types – A Comprehensive Guide with Examples
- Java Static Explained: Variables, Methods, and Blocks – Hands‑On Examples
- Java Primitive Data Types: A Clear Guide
- Understanding Java Variable Types: A Comprehensive Guide
- Mastering Java Generics: Simplify Sorting and Enhance Type Safety
- C++ Variable Types Explained: Memory, Limits, and Operations
- Understanding Variable Scope in C++: Local vs Global Variables