How to use the var keyword in Java? Example Tutorial

javinpaul - Apr 2 '19 - - Dev Community

Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.

How to use the var keyword in Java? Example Tutorial

Hello everyone! In this article, I'll discuss one of the cool features of Java 10. You guessed it right :-), I am going to talk about the introduction of the var keyword in Java. Well, it's not really a keyword --- but I'll tell you about it later.

At long last...

Finally, Java has gotten the var keyword to declare local variables. This allows you to declare a variable without its type. For example, instead of doing this:

String str = "Java"

you can now just say this:

var str = "Java".

This may not sound like much to gain when you're declaring a String or an int variable but think about complex types with generics, for example. This will surely save a lot of typing, and will also improve the readability of the code.

A little background

Java developers have long been complaining about boilerplate code and the ceremonies involved while writing code. Many things which take just 5 minutes in languages like Python, Groovy, or JavaScript can take more than 30 minutes in Java due to its verbosity.

If you have coded in Scala, Kotlin, Golang, C# or any other JVM language, then you know that they all have some kind of local variable type inference already built into the language.

For example, JavaScript has let and var, Scala and Kotlin have var **and **val, C++ has the auto, C# has var, and Go supports this by declaration with the := operator.

Until Java 10, Java was the only language which didn't have local variable type inference or support for the var keyword.

Though type inference was improved a lot in Java 8 with the introduction of the lambda expression, method references, and Streams, local variables still needed to be declared with a proper type. But that's now gone! Java 10 has a feature, JEP 286: Local-Variable Type Inference, which will allow declaring local variables without type information and by just using the var keyword.

Let's take a closer look.

Java 10 var keyword examples

Here are some examples of Java 10's var keyword:

var str = "Java 10"; // infers String

var list = new ArrayList<String>(); // infers ArrayList<String>

var stream = list.stream(); // infers Stream<String>

As I said, at this point you may not fully appreciate what var is doing for you. But look at the next example:

var list = List.of(1, 2.0, "3")

Here, the list will be inferred into List<? extends Serializable & Comparable<..>> which is an intersection type, but you won't have to type the full type information. var makes the code much easier to write and read in this case.

In the next section, we'll see some more examples that'll help you learn how to write concise code using var in Java 10.

How to write concise code using the var keyword in Java

The use of the var reserve word also makes your code concise by reducing duplication --- for example, the name of the Class which comes on both the right and left-hand side of assignments as shown in the following example:

ByteArrayOutputStream bos = new ByteArrayOutputStream();

Here ByteArrayOutputStream repeats twice, and we can eliminate that by using the var feature of Java 10 as shown below:

var bos = new ByteArrayOutputStream();

We can do similar things while using try-with-resource statements in Java, for example, this

try (Stream<Book> data = dbconn.executeQuery(sql)) {
return data.map(...) .filter(...) .findAny();
}

can be written as follows:

try (var books = dbconn.executeQuery(query)) {
return books.map(...) .filter(...) .findAny();
}

These are just a few examples. There are a lot of places where you can use var to make your code more concise and readable, many of which you can see on Sander's Pluralsight course What's New in Java 10.

It's a paid course but you can check out this 10-day free trial.

when to use var keyword in Java

For those programmers who have used Groovy or Scala, the introduction of var makes it seem like Java is going the Scala way...but only time will tell.

For now, we can just be happy that** var makes it easier to declare a complex local variable in Java 10.**

And do note: the local variable type inference of the Java 10 var keyword can only be used to declare local variables (for example, any variable inside the method body or code block).

Can you use var to declare member variables in Java?

You cannot use var to declare member variables inside the class, method formal parameters, or return type of methods.

For example, this example of var is OK:

public void aMethod(){
var name = "Java 10";
}

But, the following example is NOT OK:

class aClass{
var list; // compile time error
}

So, even though this new Java 10 feature is eye-catching and looks good, it still has a long way to go. Still, you can start using it to further simplify your code. Less boilerplate code always means better and more readable code.

Important points about this new var keyword

Now that you know that you can declare local variables without declaring the type in Java 10, it's time to learn a few important things about this feature before you start using it in your production code:

  1. This feature is built under JEP 286: Local-Variable Type Inference and was authored by none other than Brian Goetz. He's the author of Java Concurrency in Practice, one of the most popular books for Java developers.

  2. The var keyword allows local variable type inference, which means the type for the local variable will be inferred by the compiler. Now you don't need to declare it.

  3. The local variable type inference or Java 10 var keyword can only be used to declare local variables, for example inside methods, on initializers code block, indexes in the enhanced for loop, lambda expressions, and local variables declared in a traditional for loop.

You cannot use it for declaring formal variables and return types of methods, for declaring member variables or fields, on constructor formal variables, and any other kind of variable declaration.

  1. Despite the introduction of var, Java is still a statically typed language and there should be enough information to infer the type of the local variable. If not, the compiler will throw an error.

  2. The var keyword is similar to the auto keyword of C++, var of C#, JavaScript, Scala, Kotlin, def of Groovy and Python (to some extent), and the : = operator of the Go programming language.

  3. One important thing to know is that, even though var looks like a keyword, it's not really a keyword. Instead, it is a reserved type name. This means that code that uses var as a variable, method, or package name will not be affected.

  4. Another thing to note is that code that uses var as a class or interface name will be affected by this Java 10 change. But as JEP says, these names are rare in practice, since they violate usual naming conventions.

  5. The immutable equivalent of local variables or final variables val and let is not yet supported in Java 10.


Wrapping up

That's all about the var in Java 10! It's an interesting Java 10 feature, which allows you to declare local variables without declaring their type. This will also help Java developers pick up other languages quickly, like Python, Scala, or Kotlin, because they heavily use var to declare mutable variables and val to declare immutable local variables.

Even though JEP 286: Local-Variable Type Inference only supports var and not val, it is still useful and feels more like coding Scala in Java.

Further Learning

What's New in Java 10 by Sander Mak
The Complete Java Developer RoadMap
Style Guidelines for Local Variable Type Inference in Java
JEP 286: Local-Variable Type Inference
10 Things Java Developer Should learn
The Complete Java MasterClass to learn Java Better

Thanks for reading this article. If you like this new Java 10 feature, then please share with your friends and colleagues.

If you have any questions or feedback, please drop a note and stay tuned for more Java 10 tutorials and articles here.

P.S. - If you are new to Java and want to learn Java in depth then you can also checkout The Complete Java Masterclass by Tim Buchalaka on Udemy, its a great course to learn Java in depth and its also updated to cover Java Se 11 and Java 17.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .