The ‘var’ keyword in Java
- The var keyword was first introduced in Java 10.
- It allows us to declare variables without declaring the type.
//normal declaration String message1 = "Hello world!"; //using var keyword var message2 = "Hello world";
- It would help us reduce boiler plate code.
//class name is mentioned on both sides Train train = new Train(EngineType.Electric, Type.Goods, EngineVersion.Six); //using var reduces code var train = new Train(EngineType.Electric, Type.Goods, EngineVersion.Six);
- It helps us improve code readability and makes the code less verbose.
//typical way for(Map.Entry<String, Map<String, List<String>>> entry : nestedMap.entrySet()){ //do something } //using var for(var entry : nestedMap.entrySet()){ //do something }
Somethings to keep in mind while using var
-
While the use of ‘var’ keyword might make it hard to understand the code in gerrit or other plain text editors as the data types are not explicitly mentioned, The IDE’s will show us the data type when hovering over the keyword.
-
There are some limitations for using the ‘var’ keyword:
- It cannot be assigned null. A compilation error would occur.
- It cannot be used for class variables. It can only be used for local variables (inside a method)
- var cannot be used in lambda expressions.
- You cannot use var for method signatures (in return types and parameters/arguments).
Comments