Features of Java Language

Simplifying code with VAR Keyword in Java

An Introduction

Afroz Chakure

--

In Java 10 and later, we can declare local variables with non-null initializers with the var identifier, which can help you write code that’s easier to read.

var was introduced with the purpose of serving cleaner/better readability code and NOT to amend the Type System of the Java language.

var is a reserved Type Name and not a Java keyword

In essence, we can have code that uses var as a variable, method, or package name.

We cannot have var as a class and interface name.

Type Inference in var

Type inference is used in var, which it detects automatically the datatype of a variable based on the surrounding context.

Example for var types:

Consider below example, which can be redundant and hard to read:

URL url = new URL("http://www.google.com/"); 
URLConnection conn = url.openConnection();
Reader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))

We can rewrite the example by declaring the local variables with the var identifier. The type of the variables are inferred from the context:

var url = new URL("http://www.google.com/"); 
var conn = url.openConnection();
var reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));

Common Examples using var types:

// Local variable declarations with initializers:
var list = new ArrayList<String>(); // infers ArrayList<String>
var stream = list.stream(); // infers Stream<String>
var path = Paths.get(fileName); // infers Path
var bytes = Files.readAllBytes(path); // infers bytes[]

// Enhanced for-loop indexes:
List<String> myList = Arrays.asList("a", "b", "c");
for (var element : myList) {...} // infers String

// Index variables declared in traditional for loops:
for (var counter = 0; counter < 10; counter++) {...} // infers int

// try-with-resources variable:
try (var input =
new FileInputStream("validation.txt")) {...} // infers FileInputStream

Java’s var use is NOT allowed:

  1. In Instance and Global variable declaration:
class Example {
// instance variable
var x = 100;
public static void main(String[] args) { System.out.println(x); }
}

2. As a Generic type and with a Generic type:

// Generic list using 
var<var> list1 = new ArrayList<>();

// var used with Generic type
var<Integer> list2 = new ArrayList<Integer>();

3. Without explicit initialization:

// declaration without initialization
var variable;

// This is also not valid
var variable = null;

4. With Lambda Expression:

interface myInt {
int add(int a, int b);
}

public static void main(String args)
{
// var cannot be used since they require explicit target type
var obj = (a, b) -> (a + b);

// calling add method
System.out.println(obj.add(2, 3));
}

Note:

It is possible to use var keyword with lambda expressions. For it, you need to add the var keyword with each of the lambda parameters and define an explicit target type.
Example:
myInt obj = (var a, var b) -> (a + b);

Read more from here : https://www.baeldung.com/java-var-lambda-params

5. For method parameters and return type:

class Dog {
// method1 using var as a return type
var method1() { return ("Bark"); }

// method2 using var as a parameter
void method2(var doSomething) { System.out.println(doSomething); }

public static void main(String[] args) {
// create an instance
Dog obj = new Dog();

// call method1
var res = obj.method1();

// call method2
obj.method2();
}
}

Important points w.r.t. var use

  1. Be aware of any team standards that might exist pertaining to Java’s var keyword.
  2. Don’t overuse Java’s var and make things unreadable.
  3. Use clear and unambiguous variables names.
  4. Combine final and var when appropriate.
  5. Avoid using var in nested blocks of code to avoid confusion.
  6. Use explicit types if the data type is not obvious, especially with polymorphic components.
  7. Be consistent with the use of var.

--

--