Here, we’ll discuss the significance of Var variable in Java 10 and learn how to use Java Var variable in software projects.
As many of you might have heard, Java10 was released in March 2018. It’s a short-term release from Oracle Corporation and came with a lot of new features or enhancements. One of the important features of Java10 is local variable type inference. The upcoming Java release will be in September 2018. It will be a long-term support (LTS) version of Java. Let’s look at a Java10 local variable type inference feature with an example now.
The main advantage of this feature is to increase code readability. Here’s an example:
A developer would have no problem reading the above two statements. In another example, here are some more complex statements that are kind of a pain to write:
In Java10, the var keyword allows local variable type inference, which means the type for the local variable will be converted by the compiler, so you don’t need to declare that type. Hence, you can replace the above two statements as below:
Below are the few points to remember when you declaring local variable type inference in Java 10:
1. Each statement containing the var keyword has a static type which is the declared automatically type of value. This means that assigning a value of a different type will always fail. So, Java is still a statically typed language and there should be enough information about the type of a local variable. If that's not there, compilation fails, for example:
2. Let’s look at an inheritance scenario. Assume there are 2 subclasses (Doctor, Engineer) extended from the parent class Person. Let’s say someone creates an object of Doctor, as shown below:
Note that in such cases, a variable declared with var is always the type of the initializer, and var may not be used when there is no initializer. Therefore, if you designate the on top of variable p, as shown below, compilation fails:
p=new Engineer(); // Compilation error saying
3. Illegal Use of var
As mentioned earlier, var won't work without the initializer:
In this blog, we see the new Java 10 local variable type inference feature with examples.
We are an ERP development company that nurtures a team of experienced Java developers that are capable of building high-quality software applications that are easy to scale. Our custom ERP software solutions enable enterprises to streamline their inbound/outbound processes, enhance productivity, and improve operational efficiency. For project-related queries, drop us a line at [email protected].