Understanding var in Java with Examples #Java10
Java introduced the var keyword in Java 10 to make coding easier and cleaner. var allows you to declare local variables without specifying their type explicitly. Instead, the compiler figures out the type based on the value you assign to the variable.
When to Use var
var is great when the type of the variable is obvious from the context, making your code shorter and more readable. You can use var for local variables in methods, loops, and try-with-resources statements.
Examples
Let’s look at practical examples of using var in Java:
1. Basic
public class VarExample {
public static void main(String[] args) {
var message = "Hello, Java 10!";
System.out.println(message);
var number = 10;
System.out.println("Number: " + number);
}
}j
In this example, var helps to declare message as a String and number as an int without explicitly stating their types.
2. Using var in Loops
import java.util.List;
public class VarLoopExample {
public static void main(String[] args) {
var numbers = List.of(1, 2, 3, 4, 5);
for (var number : numbers) {
System.out.println(number);
}
}
}
Here, var is used to iterate over a list of integers, making the code simpler and cleaner.
3. Working with Collections
import java.util.HashMap;
import java.util.Map;
public class VarMapExample {
public static void main(String[] args) {
var map = new HashMap<String, Integer>();
map.put("Alice", 30);
map.put("Bob", 25);
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
In this example, var is used to declare a HashMap and to iterate over its entries, making the code more readable.
When Not to Use var
While var can make your code cleaner, it’s not always the best choice. Avoid using var when:
- The type is not clear from the context.
- The type is complex and readability is important.
- It makes the code harder to understand.
Conclusion
The var keyword in Java helps you write cleaner and more concise code by allowing the compiler to infer the type of local variables. While var can simplify your code, it’s important to use it wisely to keep your code easy to read and maintain.
By using var in your Java projects, you can take advantage of modern Java features while keeping your code clean and efficient.
Happy coding ! Share , Follow :)