Advantages/Drawbacks of “var” in Java 10

  • A+

AFAIK, var is not keyword in Java. It is reserved type name. I wonder that in what circumstances we should use/avoid it. Are there principles about its usage?

import java.util.HashMap;  public class Test {     public static void main(String[] args) {         var x = new HashMap<> (); // legal         var y = new HashMap<String, Integer>(); // legal          var z = "soner"; // legal         System.out.println(z);          var umm = null;  // xx wrong xx //         var foo; // xx wrong usage without initializer xx //          var var = 5; // legal      } } 

I know one reason, that we actually use in our project. Whenever there is a variable that is "big" we replace it with var. For example:

 public void test(){      CreateEmailEsignTransactionAsync job = new CreateEmailEsignTransactionAsync(... some input);       // vs       var job = new CreateEmailEsignTransactionAsync(... some input)  } 

I find the second example a lot more readable, and this is how we mainly use it.

There is another example where this could be used (but I am not using it so far). Previously this was possible via chaining only for lambda expressions for example, as this would be a type known by the compiler only - they could not be declared.

 public void test() {         var test = new Object() {             public void go() {              }         };          test.go();     } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: