Java 10: See what's new with var

Figure 0: Java 10: A look at the new ways to play var

With a new release cycle every six months, Oracle has redefined its versioning strategy for Java and launched Java 10 on March 20.

This release introduces 12 enhancements as defined by JEPS (JDK Enhancement Proposal). One of them is local variable type inference (JEP 286).

In this release, the var keyword was introduced, which allows the compiler to infer the type of a local variable using its initializer recommendation. This feature is common in other languages ​​such as Swift, Scala, Go, C#, etc.

In Java 10, var is not a keyword, just a reserved type name. The reason is also to avoid some conflict or influence on the originally developed code, including variable, method or package names. That is, developers can still use var as the name of a variable, method, or package.

In Java, this feature is limited to initializing local variables, index-enhanced loops, and local variables declared in the body of a traditional for loop.

Let's look at some examples where var can help developers:

jshell> var a = 10;

a ==> 10

jshell> var b = 20;

b ==> 20

jshell> var sum = a + b;

sum ==> 30

In the above example, you may not see some usefulness of the var keyword.

Now let's look at a situation where we can store lists of different types of data.

For example, we want to create a list that contains data of different data types, such as List.of(1, "Java", 21.2). In this case, how should the developer determine the data type in the List?

The solution is to use var. After using var, the compiler automatically converts the List in the java.util.ImmutableCollections class. Let's give it a try.

jshell> var list = List.of(1,"Java 10",12.3)

list ==> [1, Java 10, 12.3]

jshell> list.getClass().getName()

$5 ==> "java.util.ImmutableCollections$ListN"

Is it interesting? There may be many more such situations.

Now, let's look at the usage of var with the traditional for loop.

jshell> for(var i = 1 ; i  var number = 10;

...> System.out.println(" i = " + i + " number = " + (number + i));

...> }

i = 1 number = 11

i = 2 number = 12

i = 3 number = 13

i = 4 number = 14

i = 5 number = 15

i = 6 number = 16

i = 7 number = 17

i = 8 number = 18

i = 9 number = 19

i = 10 number = 20

var can also be used in enhanced for loops. Take a look at the following code snippet:

jshell> for(var language : languages) {

...> var hello = "Hello";

...> System.out.println(hello + " " + language);

...> }

Hello Java

Hello Scala

Hello Go

Hello Swift

Note, however, that var does not apply to method/constructor/try/catch and method return types, variable instances or other variable declarations.

1. var in Java cannot be used as a variable declaration. The compiler looks for an initializer and infers the type of the variable.

code show as below:

jshell> var a;

| Error:

| cannot infer type for local variable a

| (cannot use 'var' on variable without initializer)

| var a;

| ^----^

2. It cannot be used with method parameters and method return types. Because the compiler cannot infer which type of var is substituted at runtime.

code show as below:

jshell> void sum(var a, var b) {

...> var c = a + b;

...> System.out.println(c);

...> }

| Error:

| 'var' is not allowed here

| void sum(var a, var b) {

|          ^-^

| Error:

| 'var' is not allowed here

| void sum(var a, var b) {

|                 ^-^

jshell> var sum(int a, int b) {

...> var c = a + b;

...> return c;

...> }

| Error:

| 'var' is not allowed here

| var sum(int a, int b) {

| ^-^

3. It cannot be used as an instantiated variable. Normally, we cannot initialize instance variables, but var is restricted to initialization, and developers can use constructors or getter-setters to read or initialize/change the value of variables.

code show as below:

shell> class Java10Tester {

...> var field = 100;

...> public void display() {

...> System.out.println("field = " + field);

...> }

...> }

| Error:

| 'var' is not allowed here

| var field = 100;

| ^-^

4. Cannot be used for class variables.

jshell> class Java10Tester {

...> static var field = 100;

...> public void display() {

...> System.out.println("field = " + Java10Tester.field);

...> }

...> }

| Error:

| 'var' is not allowed here

| static var field = 100;

|        ^-^

5. It cannot be initialized to a NULL value. NULL does not belong to any specific data type, the compiler cannot infer the data type of the variable.

code show as below:

jshell> class Java10Test

jshell> var value = null;

| Error:

| cannot infer type for local variable value

| (variable initializer is 'null')

| var value = null;

| ^---------------^

6. Variables created with var cannot be reassigned with a different data type. The data type of a variable initialized with var is only inferred at compile time from the data type of the initializer and cannot be changed.

jshell> var a = 10

a ==> 10

jshell> a = "Hello"

| Error:

| incompatible types: java.lang.String cannot be converted to int

| a = "Hello"

| ^-----^

summary

We've seen some instances where var can and cannot be used before. We can draw the following conclusions:

1) The impact of code readability.

2) The availability of var is limited. The developer must know where he/she can use it and where not.

I wish Java would do more for the developer and provide a less restrictive feature.

Recommend an exchange learning group: 697579751 It will share some videos recorded by senior architects: Spring, MyBatis, Netty source code analysis, principles of high concurrency, high performance, distributed, microservice architecture, JVM performance optimization, these become architects Necessary body of knowledge. You can also receive free learning resources, which are currently benefiting a lot:

Hope you like this article, welcome to share and like.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324932028&siteId=291194637