- Java 10 - Discussion
- Java 10 - Useful Resources
- Java 10 - Quick Guide
- Java 9 Tutorial
- Java 8 Tutorial
- Java Tutorial
- Java 10 - Thread-local Handshake
- Java 10 - Root Certificate
- Java 10 - Consolidated JDK Forest
- Java 10 - Heap Allocation
- Java 10 - Locale Enhancement
- Java 10 - Enhanced Garbage Collection
- Java 10 - Class-Data Sharing
- Java 10 - JIT Compiler
- Java 10 - Deprecated Features & Options
- Java 10 - Removed Features & Options
- Java 10 - New APIs & Options
- Java 10 - Local Variable Type Inference
- Java 10 - Time Based Release Versioning
- Java 10 - Environment Setup
- Java 10 - Overview
- Java 10 - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java 10 - 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 initiapzed at time of declaration otherwise compiler will not be infer and will throw error.
Local variable inference is available inside initiapzation 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; pubpc class Tester { pubpc static void main(String[] args) { var names = List.of("Jupe", "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.
Jupe Robert Chris Joseph Jupe Robert Chris JosephAdvertisements