Java 10 – var

The most noticeable added feature for developers in the java version 10 release. I have used jshell to illustrate the examples.

Before Java 10 
Using var  

What is var? 

Var is a type inference of local variables with initializers. This feature is only available as a mutable local variable and an immutable equivalent of a local variable is not supported in Java 10.

General Q & A 

How does var work?

Through not assigning the data type, the compiler interprets the data type from the initializer on the right hand side.

Is var a keyword? 

No, it is not a keyword but a reserved type name. Reason being that this helps with backward compatibility. Meaning, this will not affect if var was used as variable, method, or package. However, classes and interfaces will be affected if they are declared as var. 

Why would you use this? 

Helps to reduce boilerplate code, making your code more readable.  

What can you use this for? 

What can’t you use this for? 

Declared without and initializer. 

Initialized with null  

Final Thoughts 

This works well with the JShell tool and personally, I mostly use this in local variable declaration in methods.  It has become the norm for software engineers, to learn multiple languages, this could be seen as a skill transferable, as var is more commonly used in other languages like, Python, JavaScript, Kotlin, etc.  

1 thoughts on “Java 10 – var

  1. Pingback: Java Versions & Features - Spaghetti Code Jungle

Leave a Reply

Your email address will not be published. Required fields are marked *