‘var’ in Java: The smart shortcut you should be using.
Java being a statically typed language, we must declare variable’s type before using it. This makes code predictable, easy to read and…
‘var’ in Java: The smart shortcut you should be using.
Java being a statically typed language, we must declare variable’s type before using it. This makes code predictable, easy to read and understand, and safe, but it can also cause issues, when the datatype of the input is not pre-decided as it may depend on the user as well as lead to a lot of repetitive typing especially when working with long generic types.
But with Java 10 a small but powerful feature was introduced: The ‘var’ keyword. Despite its name, ‘var’ is not a new datatype. It allows the compiler to infer the type of a local variable based on the value assigned to it.
Let’s see how ‘var’ works, its rules, benefits and the best practices.
1.What is ‘var’ in Java ?
‘var’ is a reserved type name introduced in Java 10 that enables local variable type inference.
Example:

Here, the compiler examines the value “Hello World” and determines that “message” is a “String”. After compilation this is same as:
String message = “Hello World” ;
2. How ‘var’ works ?
‘var’ does not make Java dynamically typed — the type is still determined at compile time. Once a type is inferred it cannot be changed.

3. Rules for using ‘var’.
(i) Must be initialized — The compiler needs a value to infer the type.
(ii) Only for local variables — Can be used inside methods, constructors, and blocks but not for fields, parameters or return types.
(iii) Type is fixed — Once inferred it can not be changed.
4. Benefits of ‘var’
(i) Reduces boilerplate, great for long generic types.

(ii) Improves readability in loops

(iii) Still type-safe — You get all benefits of compile-time checks.
5. Misconceptions about using ‘var’.
(i) Java is now dynamically typed — No, type is still determined at compile time.
(ii) ‘var’ works everywhere — No, only local variables.
(iii) ‘var’ is unsafe — No, it’s just as safe as explicit typing.
Conclusion
The ‘var’ keyword is a small change with a big impact on Java code readability. By letting the compiler do the typing for you, it reduces clutter without compromising safety. Tip: Pair ‘var’ with meaningful variable names. Since the type isn’t visible at first glance, a clean name makes your code much easier to understand.
메타데이터
- post_id
- 5ae93f5edd9e
- slug
- var-in-java-the-smart-shortcut-you-should-be-using-5ae93f5edd9e
- url
- https://medium.com/@tanmayyashu29/var-in-java-the-smart-shortcut-you-should-be-using-5ae93f5edd9e
- canonical_url
- https://medium.com/@tanmayyashu29/var-in-java-the-smart-shortcut-you-should-be-using-5ae93f5edd9e
- author_url
- https://medium.com/@tanmayyashu29
- status
- ok
- fetched_at
- 2026-07-18 09:37:53