Long, long ago, we wrote code that was careful about the data types of variables, such as the following:

Enumeration: Despite the addition of enumerations in JDK 5, constants of type CONSTANT_Class_info in the Class file constant pool remain semantically unchanged and are symbolic references to a Class or interface without enumerations. No “enumeration symbol reference” constants such as “CONSTANT_Enum_info” have been added. So defining constants with the enum keyword is an illusion created by the Javac compiler, even though it looks syntactically like defining a class using the class keyword and defining an interface using the interface keyword. From a bytecode perspective, Enumerations are simply plain Java classes that inherit from java.lang.enum and automatically generate values() and valueOf() methods, so enumerations are also referred to.

In JDK 10, however, we have a new option. In JDK 10, we have added the var local variable inference function, with which we can happily forget about datatypes. Let’s take a look.

1. Use comparison

Next, we will use the way of comparison to experience the role of VAR.

Scenario 1: Defining a string

Old writing:

String str = "Hello, Java.";
Copy the code

A new method:

var s = "Hello, Java.";
Copy the code

PS: The old version refers to the version before JDK 10, while the new version refers to the version after JDK 10 (including JDK 10).

Scenario 2: Adding values

Old writing:

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

PS: When adding different types (int+ double), num3 will be upgraded to double.

A new method:

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

Scenario 3: Collection

Old writing:

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

A new method:

var list = new ArrayList<>();
list.add("Hello");
list.add("Java");
Copy the code

Scenario 4: Loops

Old writing:

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

A new method:

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

Scenario 5: Using Lambda

Old writing:

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

A new method:

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

2. Advantages analysis

As you can see from the examples above, VAR has two obvious advantages: improved code readability and named alignment.

① Improved readability

Before we used var, we had the following situation if the type name was long:

InternationalCustomerOrderProcessor<AnonymousCustomer, SimpleOrder<Book>> orderProcessor = 
    createInternationalOrderProcessor(customer, order);
Copy the code

When limiting each line to 150 characters, variable names are pushed to the next line, making the whole code less readable. But when we use var, the code looks like this:

var orderProcessor = createInternationalOrderProcessor(customer, order);
Copy the code

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

② Naming and alignment

When var is not used, the code looks like this:

// An explicit type
No no = new No();
AmountIncrease<BigDecimal> more = new BigDecimalAmountIncrease();
HorizontalConnection<LinePosition, LinePosition> jumping =
  new HorizontalLinePositionConnection();
Variable variable = new Constant(6);
List<String> names = List.of("Java"."Chinese Community");
Copy the code

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"."Chinese Community");
Copy the code

As you can see from the above code, the names are aligned and the code is much more elegant.

3. Use rules & counterexamples

The realization of the var from JEP 286 (286) to improve the proposal, details of address: openjdk.java.net/jeps/286

As you can see from the heading “Local Variable Type Inference” in JEP 286, var can only be used for local variable declarations, that is, var must satisfy the following conditions:

  • It can only be used on local variables;
  • Must be initialized when declared;
  • Cannot be used as method parameters and global variables (class variables).

PS: Because the implementation of var must type infer from the code on the right, it cannot be assigned null or uninitialized.

Counterexample 1: Null is not initialized and assigned

Counterexample 2: Mid-stream type changes

Counterexample 3: Global variables

Counterexample 4: As a return value

4. Principle analysis

After the previous use we have a preliminary understanding of VAR, but what is the implementation principle of VAR?

To understand how it works, we compiled the following code (using the commandjavac MainTest.java) :Then we open the compiled class with a decompiler and find:varInstead, the data types are identified, as shown below:From this we can draw the conclusion that:varThe implementation of a keyword is closely related to its name,varThis is only local type inference, and it only works at Java coding time and compilation time, when a class is compiled as a class file,varIt becomes a set of defined data types (inferred).So we can takevarCommonly known as Java syntactic sugar, using it allows us to quickly and elegantly implement business code, butvarIt doesn’t exist at the bytecode level.

conclusion

In this article we introduced the use of var (local type inference). It can be used in variable declarations of local variables, for, and Lambda, but it cannot be used in declarations of global variables, nor as a return value of methods, and must be initialized (nor null) when declared. Using var improves code readability and name alignment by type inference at compile time using the code to the right of the equals sign, and then replacing var with the specified data type.

Follow the public account “Java Chinese community” to send “interview”, I organized the latest interview review materials.