Java 10 Combat 1th: local Variable type inference

Source: Internet
Author: User

Now Java 9 has been abandoned directly to Java 10, before also the Java 10 new features of the article, it is time to start the actual combat Java 10.

Today to combat is the most important feature of Java 10: Local Variable type inference, we all know is the var keyword, but how to use, and pay attention to what points?

Let's take a few examples to explain the new feature of local variable type inference!

What is local variable type inference
var javastack = "javastack";System.out.println(javastack);

As you can see, the local variable type inference is that the left type uses the definition directly, var instead of writing the specific type, the compiler automatically infers the type based on the expression on the right, as above String .

var javastack = "javastack";

is equal to:

String javastack = "javastack";
Example of using local variable type inference

Since it is called a local variable type inference, which can only be used in local variables, here are more examples of usage.

1, the literal definition of local variables

private static void testVar() {    var javastack = "javastack";    System.out.println(javastack);}

2. The Receive method return value defines the local variable

private static void testMethod() {    var javastack = getJavastack();    System.out.println(javastack);}public static String getJavastack() {    return "javastack";}

3. Define local variables in the loop

private static void testLoop() {    for (var i = 0; i < 3; i++) {        for (var m = 10; m < 15; m++) {            System.out.println(i + m);        }    }}

4. Generics combined with local variables

private static void testGeneric() {    // 表达式1    List<String> list1 = new ArrayList<>();    list1.add("javastack");    // 表达式2    var list2 = new ArrayList<>();    list2.add(2018);    // 表达式3    var list3 = new ArrayList<String>();    list3.add("javastack");}

After expression 1 &lt;&gt; , the JDK 1.7+ begins without a specific type, and is indicated on the interface.

In Expression 2, if used var , it &lt;&gt; will be the default Object , so you can add any type.

In Expression 3 &lt;&gt; , a String is used to specify a generic type.

Local variable type inference cannot be used in the following scenarios

1. class member Variable type

// 编译报错private var javastack = "Java技术栈";

2. Method return type

/** * 编译报错 * @return */public static var getJavastack(){    return "Java技术栈";}

3. LAMBDA expression

private static void testLambda() {    Runnable runnable = () -> System.out.println("javastack");    // 编译报错    // var runnable = () -> System.out.println("javastack");}

The above 3 kinds of scenes are certainly not used var , other occasions need to be verified.

Advantages and disadvantages of local variable type inference

Pros: Simplify code

CopyOnWriteArrayList list1 = new CopyOnWriteArrayList();ConcurrentModificationException cme1 = new ConcurrentModificationException();DefaultServiceUnavailableRetryStrategy strategy1 = new        DefaultServiceUnavailableRetryStrategy();var list2 = new CopyOnWriteArrayList<>();var cme2 = new ConcurrentModificationException();var strategy2 = new DefaultServiceUnavailableRetryStrategy();

From the above code, it can be seen that a long definition type will be very lengthy code, using Var greatly simplifies the code writing, while the type of unity appears to be very aligned code.

Cons: Masking types

var token = new JsonParserDelegate(parser).currentToken();

Look at the above code, do not go to see the return result type, who knows what type is returned? So it is best not to use this situation var , but to use specific abstract classes, interfaces, or instance types.

The var keyword principle

var is actually a syntactic sugar added to Java 10, and the actual type is automatically inferred during compilation, with the compiled bytecode consistent with the actual type, as shown in the following example.

private static void testByteCode() {    String javastack1 = "javastack";    var javastack2 = "javastack";}

After compiling into bytecode:

private static testByteCode()VL0LINENUMBER 22 L0LDC "javastack"ASTORE 0L1LINENUMBER 23 L1LDC "javastack"ASTORE 1L2LINENUMBER 24 L2RETURNL3LOCALVARIABLE javastack1 Ljava/lang/String; L1 L3 0LOCALVARIABLE javastack2 Ljava/lang/String; L2 L3 1MAXSTACK = 1MAXLOCALS = 2

It can be seen that the javastack1 javastack2 virtual machine is aware of the local variable type: java.lang.String the virtual machine does not know the Var, so it var is not magical.

OK, this time the Java 10 local variable type inference actual combat article is here, follow-up brings more Java 10 combat aspects of the article.

Recommended: Spring Boot & Cloud's Strongest technology tutorials

Scan attention to our public number, dry foods updated daily.

Java 10 Combat 1th: local Variable type inference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.