Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

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

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

  1. Java Primitive Data Types: A Complete Guide with Examples
  2. Master Java Operators: Types, Syntax, & Practical Examples
  3. Mastering Java Type Casting: From Widening to Narrowing and Beyond
  4. Java Variables and Data Types – A Comprehensive Guide with Examples
  5. Java Static Explained: Variables, Methods, and Blocks – Hands‑On Examples
  6. Java Primitive Data Types: A Clear Guide
  7. Understanding Java Variable Types: A Comprehensive Guide
  8. Mastering Java Generics: Simplify Sorting and Enhance Type Safety
  9. C++ Variable Types Explained: Memory, Limits, and Operations
  10. Understanding Variable Scope in C++: Local vs Global Variables