Java Var Keyword


The var keyword allows for local variable type inference, where the compiler infers the type of a variable based on the assigned value. It reduces the need for explicit type declarations, making the code more concise and readable.

Here’s how to use var in various scenarios:

Initializing Variables:

var name = "John"; // Infers type as String
var age = 25; // Infers type as int
var list = new ArrayList<String>(); // Infers type as ArrayList<String>

Loop teration:

var numbers = List.of(1, 2, 3, 4, 5);
for (var number : numbers) {
    // Inferred type of 'number' is Integer
    System.out.println(number);
}

Method Return Types:

public var process() {
    // Inferred type based on the return value
    return someMethod();
}

Lambda Expressions:

var runnable = (Runnable) () -> {
    // Code implementation
};

Method Arguments:

public void processName(var name) {
    // Inferred type based on the argument passed
    System.out.println(name);
}

It’s important to note that while var allows for type inference, the variable is still strongly typed, and its type is determined at compile time. The inferred type cannot be changed once assigned.

However, it’s recommended to use var judiciously and consider readability. It’s best suited for cases where the type is obvious or when working with complex generic types.

Additionally, some considerations when using var:

  • Avoid excessive use or nested inference that may reduce code clarity.
  • Provide meaningful variable names to enhance code understanding.
  • Be aware of cases where the inferred type may differ from what you expect, such as when working with mixed-type expressions.

It’s worth mentioning that var is not meant to replace explicit type declarations entirely. It’s a useful tool to enhance code readability and reduce boilerplate code in certain scenarios.

Overall, var improves the developer experience by reducing verbosity and enhances code readability without compromising the strong typing of the Java language.

Note: The var keyword is available in Java 10 and later versions.