Var in java?

Var in java?

If you are like me who picked up java when it was released a quarter of a century back, chances are that you will appreciate this.

The backend for one of our projects is in java and spring boot. As part of best practices of software development, we configured our code to be analysed by Sonarqube, an awesome tool for code quality.

As we looked at the different types of issues reported by the tool, we spotted this one

Declare this local variable with “var” instead.

Hey, was I reading this right? This is java code and not javascript, right? Even in javascript, we now should be using let and const to scope the variables correctly. var in java? On clicking the Why is this an issue? link, we were presented with more details.

Quoting from the details displayed by Sonarqube

Local-Variable Type Inference should be used

In Java 10 Local-Variable Type Inference was introduced. It allows you to omit the expected type of a variable by declaring it with the var keyword.
While it is not always possible or cleaner to use this new way of declaring a variable, when the type on the left is the same as the one on the right in an assignment, using the var will result in a more concise code.
This rule reports an issue when the expected type of the variable is the same as the returned type of assigned expression.

Boy, weren’t we glad we decided to use Java 11, rather than Java 8 to build this application? As you can see above, this feature came into Java in Java 10.

Comments are closed.