How to Use var in Java: Tips from the Official Style Guide
Do you know the difference between a local variable and an instance variable in Java?
Let’s break it down:
Local variables are declared inside methods, constructors, or blocks. They are created when the method is called and destroyed when the method finishes.
Instance variables are declared inside a class but outside any method. They belong to the object and exist as long as the object is in memory.
What About var
?
You might already be familiar with var
, introduced in Java 10 through JEP 286: Local-Variable Type Inference. Even though we’re now on Java 24, it’s still important to understand how and when to use it.
As the name suggests, var
is only for local variables. That means you can’t use it for instance variables, method parameters, or return types.
The JEP 286: Local-Variable Type Inference is not a new feature, it was introduced on Java 10, we are already on Java 24, introduces the var to the Java language, however, it as the name already says, it is a feature that can be used only for local variable.
When Should You Use var
?
This is a topic with many opinions. Some developers love the cleaner syntax, while others prefer explicit types for better readability.
If you're unsure when to use var
, or whether you should use it, I wrote an article sharing my personal thoughts on the topic.
For a more in-depth and official perspective, I highly recommend the style guide created by the Amber Project team. Stuart W. Marks wrote a great piece on best practices for using var
, which you can check out here:
🔗 https://openjdk.org/projects/amber/guides/lvti-style-guide