Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java's new feature: var, data types can be thrown away?


May 31, 2021 Article blog


Table of contents


This article comes from the public number: Java Chinese Community Author: Lei ge

Many years ago, programmers had to choose the data types of variables carefully when they coded them, as follows:

 Java's new feature: var, data types can be thrown away?1

Enumeration: Although enumeration types have been added to JDK 5, the CONSTANT_Class_info type constant of the Class file constant pool has not changed semantically, is still a symbolic reference to a class or interface, has not been enumerated, and has not added an Enumeration Symbol Reference constant such as "CONSTANT_Enum_info". So defining a constant with the enum keyword, although it looks at the same level from Java syntax as defining a class using the class keyword and defining an interface with the interface keyword, is actually an illusion made by the Javac compiler, and from a bytecode point of view, enumeration is just a normal Java class inherited from the java.lang.Enum, automatically generated values() and valueOf() methods, so enumeration is also classified as a reference type.

However, when it comes to JDK 10, we have a new option, and the addition of var local variable inference in JDK 10, with which we can forget about data types, how does it work? Let's take a look.

1, the use of comparison

Next we'll use contrast to see what var does.

Scenario 1: Define the string

Old writing:

String str = "Hello, Java.";

New writing:

var s = "Hello, Java.";

PS: The old writing here refers to the version prior to JDK 10, while the new formulation refers to the version after JDK 10 that contains JDK 10.

Scenario 2: The values add up

Old writing:

int num1 = 111;
double num2 = 555.666d;
double num3 = num1 + num2;
System.out.println(num3);

PS: When you encounter a different type add-up int plus double the data type transforms upward, so num3 is upgraded to double type.

New writing:

var n1 = 111L;
var n2 = 555.666;
var n3 = n1 + n2;
System.out.println(n3);

Scenario 3: Collection

Old writing:

List<Object> list = new ArrayList();
list.add("Hello");
list.add("Java");

New writing:

var list = new ArrayList();
list.add("Hello");
list.add("Java");

Scenario 4: Loop

Old writing:

for (Object item : list) {
    System.out.println("item:" + item);
}
for (int i = 0; i < 10; i++) {
    // do something...
}

New writing:

for (var item : list) {
    System.out.println("item:" + item);
}
for (var i = 0; i < 10; i++) {
    // do something...
}

Scenario 5: Use with Lambda

Old writing:

List<Object> flist = list.stream().filter(v ->
                v.equals("Java")).collect(Collectors.toList());
System.out.println(flist);

New writing:

var flist = list.stream().filter(v ->
             v.equals("Java")).collect(Collectors.toList());
System.out.println(flist);

2, advantage analysis

As we can see from the example above, var has two obvious advantages: improved code readability and naming alignment.

(1) Improved readability

Before we use var this happens if the name of the type is long:

InternationalCustomerOrderProcessor orderProcessor = 
    createInternationalOrderProcessor(customer, order);

When you limit each line to no more than 150 characters, the variable name is pushed to the next line of display, making the entire code less readable. But when we used var the code became like this:

var orderProcessor = createInternationalOrderProcessor(customer, order);

As you can see from the code above, the longer the type, the greater the value of var (readability).

(2) Naming alignment

When you don't use var this is the case with code when you encounter the following:

// 显式类型
No no = new No();
AmountIncrease more = new BigDecimalAmountIncrease();
HorizontalConnection jumping =
  new HorizontalLinePositionConnection();
Variable variable = new Constant(6);
List names = List.of("Java", "中文社群");

After using var the code looks like this:

var no = new No();
var more = new BigDecimalAmountIncrease();
var jumping = new HorizontalLinePositionConnection();
var variable = new Constant(6);
var names = List.of("Java", "中文社群");

As you can see from the above code, after using var the naming is aligned and the entire code becomes more elegant.

3, the use of rules and counter-cases

var implementation of var comes from JEP 286 (Improvement Proposal 286), details: http://openjdk.java.net/jeps/286

As can be seen from the title of JEP 286, Local Variable Type Inference, var can only be used for local variable declarations, which means that var must meet the following criteria:

  • It can only be used on local variables;
  • The declaration must be initialized;
  • Cannot be used as method parameters and global variables (class variables).

PS: Because the implementation of var must be type inferred from the code to the right of the equivalent, it cannot be assigned null or not initialized.

Case one: null is not initialized and assigned

 Java's new feature: var, data types can be thrown away?2

 Java's new feature: var, data types can be thrown away?3

Case 2: Halfway type change

 Java's new feature: var, data types can be thrown away?4

Case three: Global variables

 Java's new feature: var, data types can be thrown away?5

Case 4: As a return value

 Java's new feature: var, data types can be thrown away?6

4, principle analysis

After the previous use we have a preliminary understanding of var but how does var work?

To find out how it works, we compiled the following code (using the command javac MainTest.java

 Java's new feature: var, data types can be thrown away?7

Then we use the decompile tool to open the compiled class discovery: var has been replaced with a definite data type, as shown in the following image:

 Java's new feature: var, data types can be thrown away?8

From this we can conclude that var implementation of the var keyword is closely related to its name, var is only a local type inference, it will only be valid during the Java encoding and compilation period, when the class is compiled as a class file, var will become a definite data type (by inference). So we can understand var colloquially as Java's syntax sugar, which allows us to implement business code quickly and gracefully, but var doesn't exist at the bytecode level.

summary

In this article, we describe the use of var (local type inference), which can be used in variable declarations for local variables, for Lambda but not in the declaration of global variables, nor as a return value for methods, and must be initialized (nor assigned null) at the time of declaration. Var var can be used to effectively improve the readability and naming alignment of your code, which is implemented by inferring the type through the code to the right of the equal sign during compilation, and then replacing var with a defined data type.

Above is W3Cschool编程狮 About the new Java feature: var, data types can be thrown away? Related to the introduction, I hope to help you.