$show=/label

Java 10 LVTI: Local Variable Type Inference Explained with Examples

SHARE:

Learn quick and practical guide to Java 10 Local Variable Type Inference. One of the most visible enhancements in JDK 10 is type inference of local variables with initializers.

Java 10 Local Variable Type Inference:

In this tutorial, We will learn what is Java 10 Local Variable Type Inference with examples.

Introduction:

Java 10 introduced a new shiny language feature called local variable type inference and One of the most obvious enhancements in JDK 10.
Type inference refers to the automatic detection of the datatype of a variable, done generally at the compiler time.

For the local variables, we can use a special reserved type "var" instead of actual type and var is not a keyword. This enhancement helps in reducing the boilerplate code.

Java 10 LVTI - Local Variable Type Inference Explained with Examples

Before java 10:

Untill Java 9 or before its version, we must have to declare the type of local variable explicitly and to initialize its value. See below compiled code snippet.

String byeNote = "Saying Good Bye to Java 9 local variables";

Introduction in java 10:

The same above code can be rewritten as below with var.

var byeNote = "Saying Good Bye to Java 9 local variables";

Observe here that right side value type is String and compiler infers the type of byeNote variable based on the right side value. So, We no need to provide the actual type.

Java authors realized that right side already type is available and why again need to mention at the left side. Hence, introduced this new concept.

In the above case, the type of byeNote is String.

Rule:

This feature is available only for the local variables with a mandatory initializer. This can not be used with instance variables, static variables, method parameters, return types etc.

Initializing the variable with a value is must, otherwise compiler can not infer the type.

Note:

Some of the people think, This will be done at run-time which is determined dynamically and usage of var will cause for the overhead to the performance.
No. This statement is wrong. Because type inference is determined at compile time.


Example on var before and after java 10:

We will see another example in before and after Java 10.

Java 9:

 // Java code for Normal local variable declaration 
import java.util.ArrayList; 
import java.util.List; 
class A { 
    public static void main(String ap[]) 
    { 
       List data = new ArrayList();
    } 

Java 10:

This code works only in Java 10 or above versions.

 var data = new ArrayList();

Var can be used in the following cases and all are valid in java 10. Tested the code.

Case 1: Static block

 static {
  var car = new Car();
 }

Case 2: Local variable

 public String getStatus() {
  var str = "Success";
  return str;
 }

Case 3: Enhanced for each loop variable


  var data = new ArrayList();
  data.add("local");
  data.add("type");

  for (String s : data) {
   System.out.println(data);
  } 

Case 4: For loop index

for (var i = 0; i < data.size(); i++) {
 System.out.println(data.get(i));
} 

Case 5: Retuned value of method

// storing getStatus method returnted value into var variable.
  var value = getStatus();
 public static String getStatus() {
      var str = "Success";
      return str; }

Illegal usage of var:

var is a keyword that can't be used in the many possible areas. we'll discuss all the areas now.

1) Without an explicit initialisation

We can't utilize local variable declarations without an explicit initialisation. This means, you cannot simply use the var syntax to declare a variable without a value. The following is invalid.

  var y;

Error:
 Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Cannot use 'var' on variable without initializer

 at examples.java.w3schools.java10.local.LocalVariable.main(LocalVariable.java:35)

2) Reiniatializing

 var n = 6;
 n = "six"; 

Error:

 Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Type mismatch: cannot convert from String to int

 at examples.java.w3schools.java10.local.LocalVariable.main(LocalVariable.java:33)
 
Here, var n is intialized with 6 which is a number and later reinitialized with String "six". This is illegal because change in type from int to String that means it can't convert String to int.   

3) var variable to null

Can't initialise a var variable to null either because null does not specify the type of the value. So this is also an illegal case.

var y = null;

Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Cannot infer type for local variable initialized to 'null' 

4) On method signatures:

    a) on method arguments:

 public void printNumber(var num) {
         System.out.println(num);
 }
 
Simply compiler will say "var is not allowed here". The following is the output when we execute this program.

    Error:

 Error: Unable to initialize main class examples.java.w3schools.java10.local.LocalVariable
        Caused by: java.lang.NoClassDefFoundError: var
 

    Saying it is not able to find the any class named with "var"

    b) on method return type

 public var printNumber(int num) {
  System.out.println(num);
 } 
 
      This is also similar to the above case (a).

Best Practices to avoid usage of Var:

There are circumstances where var can be utilized legally, however may not be a smart choice to do as such.

Practice 1: Method return area

For instance, in circumstances where the code could turn out to be less meaningful:

var status = obj.prcoessMessages();

Here, the above code looks good but makes less readable what prcoessMessages() method is returning.

Practice 2: Long steam pipeline

Here, we start with a Stream<Employee> and get an IntStream by supplying the Employee::getId to mapToInt. Finally, we call max() which returns the highest integer.

var latestEmpId = empList.stream()
   .mapToInt(Employee::getId)
   .max()
   .orElseThrow(NoSuchElementException::new);

This is the another place where it’s best to avoid var is in streams with long pipeline.

Practice 3: With the diamond operator

Diamond operator is introduced in java 7 which can cause to the unexpected result using var in below code.

var studentList = new ArrayList<>();

This code is still valid and it looks to take ArrayList<Object> that means we can add any value to the studentList as below.

studentList.add(new Student(100));
studentList.add("second");
studentList.add(new Car()); 

Able to add Student object, String object and Car object to the studentList. This is better to avoid usage in this case.

If we want to add only Student instances then declaration must be changed to

var studentList = new ArrayList();

Practice 4: non-denotable types (Anonymmous instances)

Must be careful while dealing with non-denotable instances.

var obj = new Object() {
 String name = "java";
}; 

Here created an object for anonymus class and storing the object in var obj.

If we try to reassign to new Object() then will get compile time error.

obj = new Object(); 

Error:

 Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Type mismatch: cannot convert from Object to new Object(){}

This is because the inferred type of obj isn’t Object.

Conclusion:

In this tutorial, we saw the new Java 10 local variable type inference feature with examples and best practices. var is a pretty nice little addition to the Java language in terms of productivity and readability, but the fun doesn’t stop there. But here missing is usage of var in lamda expressions.

All the example programs shown in this tutorial are on GitHub

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 10 LVTI: Local Variable Type Inference Explained with Examples
Java 10 LVTI: Local Variable Type Inference Explained with Examples
Learn quick and practical guide to Java 10 Local Variable Type Inference. One of the most visible enhancements in JDK 10 is type inference of local variables with initializers.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHum0OkbNJ02eF0OlRE0Yzh69wxKUGh4KncItyBpSCB_FdgidjiEvJ-FmtXhwgVfkbDjcRx14fkni6deNsoCl-nQ-fkOygsh5czW9vA86TvDABD3MGIC-5YIvz-ccn3n-7BoiDR9DEu3Q/s400/Java+10+LVTI+-+Local+Variable+Type+Inference+Explained+with+Examples.PNG
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHum0OkbNJ02eF0OlRE0Yzh69wxKUGh4KncItyBpSCB_FdgidjiEvJ-FmtXhwgVfkbDjcRx14fkni6deNsoCl-nQ-fkOygsh5czW9vA86TvDABD3MGIC-5YIvz-ccn3n-7BoiDR9DEu3Q/s72-c/Java+10+LVTI+-+Local+Variable+Type+Inference+Explained+with+Examples.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/05/java10-local-variables-type-inference.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/05/java10-local-variables-type-inference.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content