Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java 10: Let's Play With var

DZone's Guide to

Java 10: Let's Play With var

This introductory post into Java 10's var type name explores what you can do with local variable type inference and, more importantly, its limitations.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

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 the var of Java 10 is that it is not a keyword, 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-loops.

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 the var keyword.

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

For instance, we want to create a list that 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 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"


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

Now, let's see the usage of var with a 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 also used with enhanced for-loops. The code snippet given below can be referred to:

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


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 types. The reason is that the compiler would not be able to infer with which type var will be replaced with at 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. Variables 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 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 a few examples where we could and we could not use var. We can conclude:

  • Compromised with code readability.
  • var is very restricted with its usability, 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!

This article was first published on the Knoldus blog.

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
java ,local variable type inference ,var ,java 10

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}