Ja[Var]
Java has changed drastically in the past couple of years, introducing new features that sometimes industry professionals struggle to grasp. Despite these changes, it’s been 10 years since the release of Java 8, and many projects in the industry are still written in Java 8. This is due to the stability, familiarity, and extensive use of Java 8 features in enterprise applications.
Although Currently, the Long-Term Support (LTS) versions are Java 11 and Java 17. These versions have been widely adopted for their extended support periods, offering a balance between modern features and enterprise-grade stability. Additionally, newer versions like Java 21 and Java 22 are also released and 23 on the horizon, promising even more advancements and features that will continue to evolve the Java ecosystem.
The var keyword, introduced in Java 10, is part of this shift towards more concise and readable code.
Java Typing
Java has been a statically typed language, requiring explicit type declarations. While this provides type safety and clarity, it can sometimes lead to verbose code.
To address the verbosity of type declarations, Java 10 introduced the var keyword, allowing local variable type inference.
What is var?
var is a reserved type name used for local variable declarations with inferred types. The compiler determines the variable's type based on the value assigned to it. More like dynamically typed languages.
Basic Syntax and Usage
var message = "Hello, World!";
var number = 42;
var list = new ArrayList<String>();languages like C# its var was already there. C# introduced var earlier, allowing for similar type inference in local variables. This makes the transition to using var in Java easier for developers familiar with C#.
In dynamically typed languages like Python, you don’t need to define types at all. Python infers the type at runtime, which is different from Java’s compile-time type inference with var.
Get sunimal malkakulage’s stories in your inbox
Join Medium for free to get updates from this writer.
Usage
Local Variables
var can be used for local variable declarations, simplifying code
var name = "Alice";
var age = 30;var can also be used in enhanced for loops:
var names = List.of("Alice", "Bob", "Charlie");
for (var name : names) {
System.out.println(name);
}Traditional For Loop with var
var numbers = new int[]{1, 2, 3, 4, 5};
for (var i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}var with Streams
var numbers = List.of(1, 2, 3, 4, 5);
numbers.stream()
.filter(number -> number % 2 == 0)
.forEach(var number -> System.out.println(number));Personal Remark
The Usage of var in Java depends largely On the developers preference and experience. While var can help reduce verbosity, it might also decrease code readability.
For traditional coders who have used Java for longer time extensively, adopting var might be challenging. Additionally, developers working with multiple Java versions simultaneously might find it difficult to adjust.
However, for newer coders who have started their Developing or coding life pretty recently, var can be beneficial, but first they should understand the basics and the problem var aims to solve before using it extensively.
Benefits
//Reduce Verbority
// Before var
Map<String, List<String>> map = new HashMap<>();
// With var
var map = new HashMap<String, List<String>>();Improve Readability in simple context
//Improve Readability in simple context
// Before var
List<String> names = List.of("Alice", "Bob", "Charlie");
// With var
var names = List.of("Alice", "Bob", "Charlie");Pitfalls
//Reduce Readability in Complex Context
// Before var
Map<String, Map<String, List<String>>> complexMap = new HashMap<>();
// With var
var complexMap = new HashMap<String, Map<String, List<String>>>();it can make harder to understand the types at a glance leading problems for code maintenance and readability.
//Ambiguity and Lack of Clarity
// Before var
int count = getCount();
// With var
var count = getCount();Without knowing the return type of getCount(), it can be unclear what type count is. This ambiguity can make the code harder to understand for someone reading it for the first time.
// Without var
List<String> list = new ArrayList<>();
// With var
var list = new ArrayList<>(); // Inferred as ArrayList<Object>
list.add("string"); // This will cause a compile-time error
// Excessive use of var
var a = getAObject();
var b = a.getAnotherObject();
var c = b.getAnotherAnotherObject();It’s essential to remember that we do not write code just for ourselves or for our company. We write code that should be understandable and maintainable by others over an extended period. Code should be clear and readable so that it can evolve and remain relevant throughout the lifespan of the project or system.
Best Practices
Readability and Maintainability
While var can reduce verbosity, it's essential to balance conciseness with readability. Use var when the inferred type is obvious and enhances code clarity.
When to Use and When to Avoid var
- Use
varfor local variables with clear and obvious types. - Avoid
varwhen the inferred type is not immediately apparent or reduces code readability. - Use When the Type is Obvious:
var name = "Alice"; // name is Obviously a String- Use Explicit Types for Complex Declarations:
// Use explicit type for so that type can be readable at a glance
Map<String, Map<String, List<String>>> complexMap = new HashMap<>();- Use for Short Variable Scope: especially
// Suitable for short-lived variables within small scopes
// especially in for loops enhanced for loops
for (var entry : map.entrySet()) {
// process entry
}- Avoid in Public APIs:
// Avoid this in method signatures or public APIs
//Remember we do not write code just for ourselves.
//We write code that should be understandable and maintainable by others.
public var getName() {
return "Alice";
}Although var is a simple keyword, in a large codebase, it can be a powerful tool to reduce verbosity and improve code readability when used appropriately. However, it can be disastrous if used without consideration.
“Var in Java can reduce verbosity and improve readability (the good), but can lead to ambiguity and reduced clarity (the bad), and may cause misleading type inference and overuse (the ugly).”
By understanding the trade-offs and following best practices, developers can effectively use var to write cleaner and more maintainable code. Remember, the code we write today should be clear and maintainable to ensure it remains useful and comprehensible for future developers and throughout the lifespan of the project.
What makes a Code clean and Clean Test, Readability Readability Readability









