Java 10: Let’s play with var


Oracle is finally up to a time-bound release of java and announced the general availability of Java 10 on March 20, 2018, as part of the new six-month release cycle.

This release introduced twelve new enhancements defined by JEPS(JDK Enhancements Proposals). One of them is Local-Variable Type Inference (JEP 286).

In this release, var is introduced, which allows the compiler to infer the type of a local variable with its initializers. This feature was very common in many other languages like Swift, Scala, Go, C# etc.

An important thing to keep in mind about var of Java 10 is that it is not a keyword but just a reserved type name. A reason behind it could be to avoid any adverse effect on already written code which may contain var as any variable, method, or package name. It also means developers can still use var as a variable, method, or package name.

In Java, this feature is only restricted to local variables with initializers, indexes in enhanced for-loop, and locals declared in traditional for-loop.

Let’s see some examples where var could 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 be able to see the benefits of var keyword.

Now, let’s see a case where we want a list which could store different type of data.

For instance, we want to create a list which contains data of different data types like List.of(1,”Java 10”,12.3). In such a case, how will a developer decide the data type of the List?

A solution is var. Using var, the compiler will automatically convert the list in 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"

Isn’t it amazing? There could be many such cases.

Now, let’s see the usage of var with 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 be used with enhanced for-loop also. Code snippet given below can be referred.

jshell> for(var language : languages) {
  ...> var hello = "Hello";
  ...> System.out.println(hello + " " + language);
  ...> }
Hello Java
Hello Scala
Hello Go
Hello Swift

 

Restrictions with var:

So far, We have talked about where var could help developers.
But it is not available for method/constructor/catch formals, method return types, instance variables, or any other variable declaration.

  1. Java’s var cannot be used for variable declaration. The compiler looks for an initializer in which it will infer the type of the variable.
    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 type. The reason is that the compiler would not be able to infer with which type var will be replaced at the runtime.
    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 is not allowed for instance variables. Generally, we don’t initialize the instance variable at the time of declaration but var is restricted to be initialized and also developers use the constructor or getter-setter methods to read or initialize/change the value of instance variable.
    jshell> class Java10Tester {
      ...> var field = 100;
      ...> public void display() {
      ...> System.out.println("field = " + field);
      ...> }
      ...> }
    | Error:
    | 'var' is not allowed here
    | var field = 100;
    | ^-^
    

  4. It is not allowed 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 with a null value. Null value doesn’t belong to any particular data type so it cannot help the compiler to infer the data type of the variable.
    jshell> class Java10Test
    jshell> var value = null;
    | Error:
    | cannot infer type for local variable value
    | (variable initializer is 'null')
    | var value = null;
    | ^---------------^
    

  6. Variable created using var cannot be re-assigned with a different data type. The data type of the variable initialized using var is inferred according to the data type of its initializer at the time of compile time only 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"
    | ^-----^
    

 

We have seen few examples where we could and we could not use var. We can conclude with its following limitations.

  • Compromised with code readability.
  • var is very restricted with its usability and so the developer would have to think that where he/she could use it and where not.

I hope Java will work upon var more and will come up with a less restricted feature.

Hope you liked the blog. Thanks for reading!


knoldus-advt-sticker

References:
blogs.oracle.com
openjdk.java.net/jeps/286
dzone.com


 

This entry was posted in Functional Programming, Java. Bookmark the permalink.

One Response to Java 10: Let’s play with var

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s