Java 10 added the var keyword, which allows you to declare local variables without explicitly defining their type. Instead, the compiler deduces the type from the variable's assigned value.
var message = "Hello, World!"; // Compiler infers type as String
var count = 42; // Compiler infers type as int
Key Points About var:
- var can only be used for local variables (e.g., within methods, loops, or blocks).
- It cannot be used for method parameters, constructor parameters ,return types or fields (class-level variables).
- The type of the variable is inferred at compile-time, not runtime.
- var is not a reserved keyword but a reserved type name, meaning it cannot be used as an identifier in contexts where a type is expected.
- Java remains statically typed; var does not introduce dynamic typing.
Example Proper usage of Var
public class VarExample {
public static void main(String[] args) {
var message = "Hello, Java 10"; // String inferred
var numbers = List.of(1, 2, 3); // List<Integer> inferred
for (var number : numbers) {
System.out.println(number);
}
var map = new HashMap<String, Integer>();
map.put("Age", 25);
}
}
Points to Ponder
var number = 3.12;
// What is the type of number?
Answer: The compiler infers number as double, not float.
Why double and Not float?
- In Java, decimal literals are of type double by default, unless you explicitly specify otherwise.
- To assign a float, you must append an f or F to the literal.
for example:
var number = 3.12f; // Now the type is float
Some Interesting Facts about var Keyword
-
var
is Not Reserved Keyword -
var
can't be used without initialization Unlike regular variables, var must be initialized at declaration because the compiler needs a type to infer.
❌ Invalid Example:
var x; // ❌ Compilation error: Cannot use 'var' without an initializer
✅ Valid Example:
var x = 42; // ✅ Compiler infers int
-
var
is Just Syntax Sugar – No Performance Overhead The Java compiler erases var during compilation and replaces it with the inferred type. At runtime, there is no difference in performance between var and explicit types.
📌 Example:
var list = new ArrayList<String>();
✅ After compilation, it becomes:
ArrayList<String> list = new ArrayList<>();
-
var
can't have a null Without Explicit Type The compiler cannot infer a type from null, so var must have an explicit value.
❌ Invalid Example:
var x = null; // ❌ Compilation error: Cannot infer type from 'null'
✅ Valid Example:
var x = (String) null; // ✅ Explicit cast allows inference
🎯 Conclusion:
The var keyword is a powerful feature that makes Java code more concise while preserving static typing. However, it should be used carefully to maintain code readability and avoid ambiguity.
End
If you have reached till the end, Thanks for giving this article a read.
If you liked this article, drop a like or comment ❤ or maybe share it in your community :) , You can also drop me a follow on X 🐤 or Linked In 👨🏫
Top comments (0)