New feature of JDK10: local variable type var

brief introduction

java is remarkable in the world with its object-oriented nature and has developed vigorously.During the development of the language, in order to make the java language more concise and convenient to use, JDK is also constantly improving.

Today, this article introduces the local variable type var introduced in JDK10.

Why do we need var

Type inference is a feature of many programming languages, and the compiler can infer the actual type of a variable without specifying a specific variable type.

The emergence of type inference can make programmer's code more flexible and easier to maintain and write.In fact, we always use type inference.

More please visit www.flydean.com

The lambda expression introduced in JDK8 is a very useful example of type inference:

int maxWeight = blocks.stream().filter(b -> b.getColor() == BLUE).mapToInt(Block::getWeight)
.max();

In the example above, blocks are a Stream < Block > type, and b used in a filter does not actually specify its type; its type is inferred from Stream.

Take another example of a thread pool:

ExecutorService executorService= Executors.newSingleThreadExecutor();
Runnable runnable=new Runnable() {
    [@Override](https://my.oschina.net/u/1162528)
    public void run() {
        log.info("inside runnable");
     }
 };
 executorService.submit(runnable);

Many times, we already know what kind of variable this is from the name of the variable, so the example above can look like this if we rewrite it with var:

var executorService= Executors.newSingleThreadExecutor();
var runnable=new Runnable() {
    [@Override](https://my.oschina.net/u/1162528)
    public void run() {
         log.info("inside runnable");
     }
 };
executorService.submit(runnable);

The code is simpler and easier for programmers to write.

If the above examples do not interest you in using var, you will be happy to use VaR in the following examples.

Suppose we have a very, very long class name:

ItIsAVeryLongNameJavaClass itIsAVeryLongNameJavaClass= new ItIsAVeryLongNameJavaClass();

Whether writing is super cumbersome or not, and the code looks redundant, we can simplify it as follows:

var itIsAVeryLongNameJavaClass= new ItIsAVeryLongNameJavaClass();

Where to use var

First var represents a local variable, so only a local variable can use var.

Then var must be initialized when it is defined:

var a;  //Invalid Declaration - - Cannot use 'var' on variable without initializer
var a = 100; //Valid Declaration

var can be used in for loop:

for ( var element : elementList){
    //do something for element
}

Or this:

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

Where can var not be used

Because var is a local variable type, it cannot be used in the definition of class variables, method variables, constructors, method returns, or catch variable definitions.

public class VarIncorrectUsage {
     
    //var user;    //Not allowed as class fields
         
    //public VarIncorrectUsage(var param){    //Not allowed as parameter 
    //}
 
    /*try{
         
    } catch(var exception){    //Not allowed as catch formal 
 
    }*/
 
    /*public var returnMethod(){  //Not allowed in method return type
        return null;
    }*/
 
    /*public Integer parameterMethod( var input ){  //Not allowed in method parameters
        return null;
    }*/
}

Note that var cannot be used when the JVM cannot infer its type or there can be many types:

var ints = {1, 2, 3};
var lambda = a -> a;
var methodReference = String::concat;

In the example above, array initialization, lambda expressions and method references cannot be var.

Other var features

var is not a keyword, so we can use var for variable names:

var var = 2;   //Valid Declaration
         
int var = 2;   //Also valid Declaration

Because var is a concept introduced by JDK10, it is not downward compatible.You cannot compile var with a lower version of the compiler.

var does not affect performance, since var is type inference made by the code compiler, it does not affect performance.

summary

var is a new feature introduced in JDK10, I hope you like it.

Examples of this article https://github.com/ddean2009/ learn-java-base-9-to-20

Author: Fldean Programs

Links to this article: http://www.flydean.com/jdk10-var-local-variable/

Source: Fldean's blog

Welcome to my Public Number: program stuff, more exciting waiting for you!

Keywords: Programming Java Lambda JDK

Added by melittle on Sun, 17 May 2020 03:21:33 +0300