Have you worked on Java 8 for too long that you’ve forgotten about the newer versions of Java? That may still be the case for many projects, but some have already moved to Java 11. Others are also contemplating migrating directly to Java 17. However, Java programmers who have worked on Java 8 for too long are probably still not using the language features available in Java 11, like the var keyword. At least that is the case in our department.
But a few of us, especially those who recently achieved their Java certification, have started using the var keyword in new Java projects. It may also be true for those reviewing for Java certification.
Are you annoyed with the var keyword?
When we use the var keyword, it evokes a memory of using Javascript, which also has the var and works similarly to Java. Generally, the var keyword allows us to define a variable without specifying its data type when we assign a value to it. Then, Java determines its data type based on the value we give to the var variable.
For example, consider the following codes.
1 2 3 4 5 6 7 8 | // myAge is an int var myAge = 100; // hisAge is a long var hisAge = 100L; // herAge is a String var herAge = Long.valueOf("101"); |
Unless we use an advanced IDE like IntelliJ, the Java var keyword can be a total annoyance. For example, when the values come from a complex expression or method calls, it’s challenging to figure out the var data type immediately by reading the codes. Luckily, most of us use advanced IDEs like IntelliJ and Eclipse, which should provide hints as to what the data type of a var variable is.
Therefore, use the var keyword as often as we can or would like.
When is the keyword applicable?
Using the var Java keyword will reduce our codebase’s verbosity since we no longer have to specify the data type repeatedly. However, since Java is too verbose, the var keyword alone won’t significantly reduce the size of our codebase.