Local Variable Type Inference in Java

I have introduced to you about Type Inference in Java in the previous tutorial. If you have read it, you will probably know that this is a feature of the Java Compiler based on how the declaration, the call to determine the type of data without having to explicitly declare, reducing the code redundancy. From Java 10 onwards, Java introduces the var keyword apply Type Inference, help us no need to explicitly declare the data type of local variables in a method or code block.

For example, from Java 9 and earlier, when declaring a List variable of a String object, we will declare the following:

Result:

Local Variable Type Inference in Java

But from Java 10 onwards, you do not need to declare the type of data in front of the variable names anymore, just declare with the keyword var is.

The result is the same:

Local Variable Type Inference in Java

Determining the data type of a local variable will be based on the code that we declared. In the above example, because in the right side, we have declared new an ArrayList object, so Java Compiler will understand that this is a List variable.

If before, the variable names were declared using the diamond operator (also a Type Inference) from Java 7:

Local Variable Type Inference in Java

then you cannot use the var keyword here. Because at this time, the Java Compiler only has the Type Inference names variable to the Object data type, but to the Object object, we cannot use methods of the ArrayList object.

As I said, we can also use the var keyword in the block code as follows:

Result:

Local Variable Type Inference in Java

Or:

Result:

Local Variable Type Inference in Java

You should understand: although we can use the var keyword when writing code, but when compiling these code, the data type will be compiled to exactly the data type that we want. So, when you declare this type of data, you cannot assign it to another data type.

Eg:

Local Variable Type Inference in Java

 

Add Comment