What is var keyword in Java: Simple Explanation and Example
var keyword in Java allows the compiler to infer the type of a local variable automatically based on the value assigned to it. It was introduced in Java 10 to make code simpler and cleaner by reducing the need to explicitly write the variable type.How It Works
Think of var as a smart assistant that looks at the value you give to a variable and figures out the type for you. Instead of you saying "this is an integer" or "this is a string," var watches the value and decides the type behind the scenes.
This only works for local variables inside methods, where the compiler can see the value right away. It cannot be used for fields or method parameters because the compiler needs the exact type upfront.
Using var is like telling Java, "You handle the type for me here," which can make your code shorter and easier to read, especially when the type is obvious from the value.
Example
This example shows how var lets Java figure out the variable type automatically.
public class VarExample { public static void main(String[] args) { var number = 10; // compiler infers int var message = "Hello"; // compiler infers String var pi = 3.14; // compiler infers double System.out.println(number); System.out.println(message); System.out.println(pi); } }
When to Use
Use var when the type is clear from the value, making your code cleaner and easier to read. For example, when creating objects or working with simple values where the type is obvious.
However, avoid var if it makes the code confusing or unclear, such as when the type is not obvious or when you want to be explicit for readability.
Real-world use cases include declaring local variables in methods, especially with complex types like generics or when the exact type is long to write.
Key Points
varis used for local variable type inference in Java 10 and later.- It makes code shorter by letting the compiler decide the variable type.
- It cannot be used for fields, method parameters, or return types.
- Use it when the type is obvious to keep code readable.
- Helps especially with long or complex type names.
Key Takeaways
var lets Java automatically figure out the type of local variables.var works only for local variables inside methods, not for fields or parameters.var to improve readability when the variable type is clear from the value.var if it makes the code harder to understand.