Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Finally, Java 10 Has var to Declare Local Variables

DZone's Guide to

Finally, Java 10 Has var to Declare Local Variables

This overview of local variable type inference in Java 10 will get you off to a great start using this helpful boilerplate-busting feature.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Hello all! In this series of new features of Java 10, today, I am going to talk about what is probably the most popular and most useful new feature in Java, the introduction of the var keyword (well, it's not really a keyword, but I'll you about it later).

If I am not wrong, this feature was supposed to come in Java 9, but was dropped. Finally, Java has var keyword to declare variables. which allows you to declare a variable without their type, e.g. instead of doing String str = "Java", you can now just say var str = "Java". This may not sound like much when declaring Strings or an int variable, but consider complex types with generics. This will surely save a lot of typing and also improves the readability of code.

Java developers have long been complaining about boilerplate code and the ceremonies involved while writing code. Many things that 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, Go, C#, or any other JVM language, then you know that they all have some kind of local variable type inference already built in.

For example, JavaScript has let and varScala and Kotlin have var and val, C++ has auto, C# has var, and Go has support via declaration with : = the  operator.

Though type inference was improved a lot in Java 8 with the introduction of lambda expressions, method references, and Streams, local variables still needed to be declared with proper types — but that's now gone.

Java 10 var 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>s


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, list will be inferred into List<? extends Serializable & Comparable<..>>, which is an intersection type.

The use of var also makes your code concise by reducing duplication, e.g. the name of the Class that comes in both right and left-hand side of assignments as shown in the following example:

ByteArrayOutputStream bos = new ByteArrayOutputStream();


Here, ByteArrayOutputStream repeats twice. 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:

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


That can be written as follows:

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


These are just a few examples, of course. 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 Sander's Pluarlsight course What's New in Java 10. It's a paid course, but you can get it for free by signing up for 10-day free trial.

Finally, Java 10 has var to declare Local Variables - JDK 10 New Feature

Is Java Going the Scala or Groovy Way?

For those programmers who have used Groovy or Scala, the introduction of var might seem like Java going Scala's 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.

Anyway, the local variable type inference of Java 10's var keyword can only be used to declare local variables, e.g. any variable inside a method body or code block.

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

For example:

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

//But the following 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, but you can start using it to further simplify your code. Less boilerplate code always means better and more readable code.

Things to Remember

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 them in your production code:

  1. This feature is built under JEP 286: Local-Variable Type Inference and authored by none other than Brian Goetz, author of Java Concurrency in Practice, one of the most popular books for Java developers and probably next to only Effective Java by Joshua Bloch.

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

  3. The local variable type inference (or Java 10 var keyword) can only be used to declare local variables, e.g. inside methods, on initializer 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, declaring member variables or fields, constructor formal variables, or any other kind of variable declaration.

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

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

  6. 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.

  7. 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 the JEP says, these names are rare in practice, since they violate usual naming conventions.

  8. The immutable equivalent of local variables or final variables (val and let) are not yet supported in Java 10.

That's all about var in Java 10, an interesting Java 10 feature that allows you to declare local variables without declaring their type. This will also help Java developers pick up other languages quickly, e.g. 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 still useful and feels like Scala coding in Java.

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
java ,var ,local variable ,type inference ,java 10 ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}