Stop Repeating Yourself: Java 10’s var Explained
- Published on
- Authors
- Name
- Spaghetti Code Jungle
- @spagcodejungle

Stop Repeating Yourself: Java 10’s var Explained
Introduction
Java is powerful but notoriously verbose. Java 10, however, introduces the var keyword, making it easier and cleaner to declare local variables.
But like any powerful tool, it comes with some best practices and pitfalls. Let’s explore exactly what var is and how you can use it effectively in your Java code.
What Exactly Is var?
Firstly, let's clear a common misconception: var is not a new data type in Java. Instead, it allows Java to infer the type of a local variable automatically at compile time. In other words, you no longer have to explicitly specify the variable type when the compiler can clearly infer it from the initialization.
Quick Example
var greeting = "Hello, Java 10!"; // inferred as String
var number = 42; // inferred as int
Notice how concise yet readable this becomes.
Where Can You Use var?
You can effectively use var in the following scenarios:
- ✅ Local variables inside methods
- ✅ Enhanced for-loops
- ✅ Try-with-resources blocks
Example of Valid Usage
var names = new ArrayList<String>();
names.add("Alice");
names.add("Bob");
for (var name : names) {
System.out.println(name);
}
This keeps the code clean and reduces visual noise.
Where You Can’t Use var
Despite its convenience, var isn’t allowed everywhere. Here are some important limitations:
- ❌ Class or instance fields
- ❌ Method parameters
- ❌ Method return types
These cases require explicit type declarations to maintain clarity.
Best Practices for Using var
To use var effectively, consider the following guidelines:
- 🔍 Ensure readability: Use
varonly when the inferred type is obvious from context. - ⚠️ Avoid confusion: If the type isn't immediately clear, explicitly state it instead.
- 📖 Public APIs: Prefer explicit types in APIs to provide better documentation and usability.
Common Mistakes You Should Avoid
With great power comes responsibility! Here are common pitfalls:
- 🚧 Hiding important type information: Don't use
varwhen the explicit type significantly improves readability. - 🚧 Complex expressions: Avoid overusing
varin situations where inference makes the code harder to understand.
Why var Matters
Used wisely, var provides several significant benefits:
- 🚀 Less boilerplate: Reduces repetitive and verbose type declarations.
- 💡 Improved productivity: Developers write and read code faster and easier.
- ✨ Cleaner, clearer code: Makes your intent stand out, improving maintainability.
Conclusion
The introduction of the var keyword in Java 10 was a significant step toward a less verbose and more readable language. Remember, the goal is always clarity, not brevity alone.
By understanding when and how to use var, you can simplify your code without losing readability.
Personally, i normally use the var keyword, as a local variable in utility methods.