The var keyword in Java
Darcy DeClute
My "Scrum Master Certification Guide" is now on Amazon! || 250K+ Followers on Twitter || Mojo Maven || PSM || PSD || CSPO
Java's var keyword allows developers to declare local variables without specifying a data type such as int, long, String or char.
A new language feature introduced in the 2018 JDK 10 release, the Java var keyword performs type inference.
Java, var and inferred types
Type inference means Java will guess the data type when the variable is created, and enforce that typing throughout the program.
With Java's var keyword combined with type inference, Java programs remain strongly typed while the developer is relieved of the burden of explicitly stating the type of each variable.
Variable Declarations in Java
Here's how the Java var keyword looks when used in a program
var theMagicNumber = 7;
var theGuess = 5;
Yes, this is Java.
This is Java, and this is how you can declare local variables in Java.
Java's new language features
I'm always surprised by how many Java developers are unaware of the fact that that you can declare local variables in Java with the var keyword.
(Actually, var is not a keyword. It's a reserved word. But let's not get into that.)
The var keyword makes Java code look cleaner, but it also has another great benefit. It makes Java easier to learn!
In my article on how to write your first Java program, I used the var keyword extensively. It just makes learning easier and more fun. If you want to learn to program, Java is definitely the way to go! (Video tutorial here)
A good rule of thumb when it comes to the var keyword is that it can be used inside methods to declare local variables.
Where is Java's var not allowed?
However, the var keyword is not allowed in all context. Here are six instances where the Java var keyword is not allowed:
So there are definitely some compiler enforced rules about when to use Java's var keyword.
领英推荐
Java var keyword best practices
There are also some best practcies surrounding the use of Java's var keyword, such as:
So there you go! Java just keeps getting better and better, and Java's var keyword is a great example of that!
Get Scrum Master Certified!
By the way, my Scrum Master Certification Guide is now available on Amazon.
If you want to learn more about Scrum, and perhaps even get you PSM1, CSM or Product Owner certification, it's the right book for you!
It's helping lots of people get Scrum certified!
Software marmite with a dash of autism
1 年It's sad to see that Java is just sitting back and waiting for something new to emerge, then copying it. This sort of thing has been in Groovy (another JVM language) for years.