How to Use the var Keyword for Local Variable Type Inference in Java 10

In Java 10, the var keyword was introduced to allow local variable type inference. This means that when you declare a local variable, the compiler automatically infers its type based on the initialization value. This improves readability and reduces boilerplate code, especially when working with complex types, without compromising type safety.

Here’s a guide on how to use the var keyword:


1. Declaring and Initializing Local Variables with var

The var keyword replaces explicitly specifying the type while declaring local variables. However, you must initialize the variable at the time of declaration, as the compiler needs an expression to infer the type.

// Example of using var keyword
var message = "Hello, Java 10!";  // Inferred as String
var number = 10;                 // Inferred as int
var list = List.of("apple", "banana", "orange"); // Inferred as List<String>

Here, the type of each variable is deduced by the Java compiler:

  • message: String
  • number: int
  • list: List<String>

2. Scopes Where var Can Be Used

The var keyword can only be used in specific contexts:

a. Local Variables in Methods

public void demoVarUsage() {
    var name = "John";      // Inferred as a String
    var age = 30;           // Inferred as an int

    System.out.println(name + " is " + age + " years old.");
}

b. Loop Variables (for-each or traditional for-loops)

// for each loop
var items = List.of("A", "B", "C");
for (var item : items) {
    System.out.println(item);  // item inferred as String
}

// traditional for loop
for (var i = 0; i < 10; i++) {
    System.out.println(i);     // i inferred as int
}

c. Local Variables in Lambda Expressions

var lambda = (String x, String y) -> x + y; // Explicit lambda types
System.out.println(lambda.apply("Java", "10"));

3. Restrictions on var Usage

While var is versatile, there are limitations:

  1. Cannot Be Used Without Initialization
    var name; // Compilation error: cannot infer type
    name = "John";
    
  2. Cannot Be Used with Null Initializer
    var something = null; // Compilation error
    
  3. Cannot Be Used as a Method Parameter, Field, or Return Type
    The var keyword is limited to local variables inside methods and blocks, as well as loop variables. It cannot be used:

    • As a return type of method.
    • As a field in a class.
    • As a method parameter.
    public var getName() {    // Compilation error: 'var' is not allowed here
       return "Java";
    }
    
  4. Cannot Mix Explicit Types and var
    var name = "John", age = 30; // Compilation error
    var name = "John";
    var age = 30;               // Declare separately
    
  5. Cannot Infer Ambiguous Types
    var result = process();  // If `process()` returns Object, type can't be narrowed.
    

4. Advantages of Using var

  • Improved Code Readability: Reduces verbosity for complex types.
    var map = new HashMap<String, List<Integer>>(); // Cleaner than HashMap<String, List<Integer>>
    
  • Consistent with Type Inference: Makes Java more modern and closer to languages like Kotlin, Scala, or C#.


5. Best Practices

  • Avoid overusing var to ensure code remains understandable.
  • Use meaningful names for variables to compensate for the lack of explicit type.
  • Use var only when the type is obvious from the context.

Example Code:

package org.kodejava.basic;

import java.util.List;

public class VarExample {
   public static void main(String[] args) {
      // Using var for various local variable declarations
      var name = "Alice";                        // String
      var age = 25;                              // int
      var fruits = List.of("Apple", "Banana");  // List<String>

      System.out.println(name + " likes " + fruits);

      for (var fruit : fruits) {
         System.out.println(fruit);  // Inferred as String
      }

      var sum = add(10, 20);  // Inferred as int
      System.out.println("Sum: " + sum);
   }

   private static int add(int a, int b) {
      return a + b;
   }
}

Output:

Alice likes [Apple, Banana]
Apple
Banana
Sum: 30

The var keyword is a helpful addition, especially for simplifying local variables with inferred types, keeping code concise and readable while retaining type safety!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.