Local Variable Type Inference – var (Java 10)

For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/

The var reserved type introduced in Java 10 makes it possible for the compiler to infer the type of a local variable instead of us having to define the type. This reduces the amount of boilerplate code that is required.  In this article, let us discuss everything about the var keyword from the Java 11 certification perspective.

How does var work?

For the type inference to work, we need to use the var reserved type to declare the variable with an initializer of a known type. The type of the initializer is that helps to infer the type of the variable.

However, var cannot be used if there is no initializer, or if the variable is assigned as null or if the variable is assigned a lambda expression because in these cases, the type cannot be inferred.

Let us see some examples – let’s see what works and what does not.

Example Set1 (works)
var name = “Tina”; // here the type of the name variable is inferred as String
var emp = new Employee(); // here the type of the emp variable is inferred as Employee
var numbers = List.of{1,2,3}; // here the type of the numbers variable is inferred as List<Integer>
Example Set 2 (will not work)
var emp; // There is no initializer 
var name = null; // The variable is initialized to null
var str= (String s) -> s.length() <30;  // Lambda expressions need explicit target types

What is the advantage of using var?

The usage of var reserved type is very helpful in reducing redundancy. You can see how var helps in rewriting the redundant code in Example 1 into the more simple form in Example 2.

Example 1 (not easy to read)
File file = new File(args[0]);
BufferedReader br = new BufferedReader(new FileReader(file));
Map<String, Integer> mapFileContents = new HashMap<String, Integer>();
Example 2 (Rewriting Example 1 using var keyword)
var file = new File(args[0]);
var br = new BufferedReader(new FileReader(file));
var mapFileContents = new HashMap<String, Integer>();

You can see that Example 2 is much more crisp and concise when compared to Example 1. Thus, using the var keyword helps write clean and readable code by reducing clutter.

How to prevent a var variable from being reassigned?

A var variable can be prevented from being reassigned by declaring it as final.

Consider the below example.

final var nameList = List.of("seema", "sindhu");
nameList = new ArrayList<>(); // Compiler error 

Here the variable nameList is declared as a final variable. Hence reassigning a new ArrayList to this variable will cause a compile time error.

Can you use var where the variable is initialized to null?

No, the compiler cannot infer the type if the variable is null.
For example, the following is illegal.

var price = null; 

Can you use var with compound declarations?

No, var cannot be used with compound declaration. For example, the below code does not compile.

var age = 23, salary= 1000.0;

Can you use var for instance/static variables in a class?

No, var can be used only for local variables.

What are the guidelines for using var?

  • Choose variables that provide useful information
  • Minimize the scope of local variables
  • Consider var when the initializer provides sufficient information to the reader
  • Use var to break up chained or nested expressions with local variables
  • Don’t worry too much about “programming to the interface” with local variables
  • Take care when using var with diamond or generic methods
  • Take care when using var with literals

For more details on these guidelines,  please refer https://openjdk.java.net/projects/amber/LVTIstyle.html 

Quiz

Which of the following code fragments compile without errors?
A. var numberList = new ArrayList<Integer>();
   for (var num : numberList) {
	System.out.println("num is" + num);
   }
B. var numberList = new ArrayList<Integer>();
   numberList = new LinkedList<>();

C. private var getModelName() {
      return “xyz”;
   }
D. var list = new ArrayList<>();
   list.add(100);
   int i = list.get(0);

To view the answer/explanation of the above question and more certification practice questions on var, please visit http://talks.skilltoz.com/quiz-using-var-in-java/

Leave a Reply

Your email address will not be published. Required fields are marked *