DEV Community

loading...

A Taste of Dynamic Typing in Java using the var keyword

javinpaul profile image javinpaul Updated on ・8 min read

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


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.


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 in 2021
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.

Discussion (15)

pic
Editor guide
Collapse
skuzzle profile image
Simon Taddiken

It's worth mentioning that var is not intended to replace all your explicitly typed local variable declarations. It need to be applied with caution in order to not screw up the readability of your code.
For instance, the example above with the OutputStream declaration is not really chosen carefully. With var you are forced to put more emphasis on the naming of your variables. The statement from the example above could have looked like this:

var bos = processFile();

Here you have no clue about what bos might be. Using acronyms like bos is a bad practice anyway but may become painful when using var. Use proper naming like this:

var outputStream = processFile();

Also it might not be the best to compare Java's var with JavaScript's var as the latter is typed entirely dynamical.

Collapse
abstratt profile image
Rafael Chaves

I'd question the practice of including the type name in the variable name. Good names denote role or purpose, not type.

In your example, it would matter what the data in the file is going to be used for (say, contentsToCompress, imageContents, dataToSort etc).

Collapse
javinpaul profile image
javinpaul Author

I completely agree with you that naming becomes even more important with var now. A variable name like "bos" does make sense when you have ByteArrayOutputStream as type but with var, yes, we got to be more careful. Thanks for highlighting that part.

Collapse
lluismf profile image
Lluís Josep Martínez

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. This is such a bullshit. Variable declaration is a very small part of a class/method. Let's say a 5% of the total. If not declaring the type removes 50% of the declaration, the total gain is about 2%. Nothing to fuss about!

Collapse
javinpaul profile image
javinpaul Author

That's true and that's why Java is not for writing scripts or quick utilities but at the same time, I have found managing a large and super large project in Java much easier than let's say Python or JavaScript. Though I am not a Python or JavaScript expert, I have just happened to work on that, but that's what I have felt during my slightly limited exposure.

Collapse
diegopm profile image
Collapse
milan997 profile image
milan997

Haven't really understood it in Java or C#, I don't understand the gains except for not having to type a few characters, and you're loosing that nice readability in statically typed languages.

Also, var should be illegal now in javascript, having let and const.

Collapse
javinpaul profile image
javinpaul Author

It's not just typing but readability improves with more concise code but yes, you got to be more careful with variable names now because you just have one identifier to use to convey your intention and what the variable is and what it does.

Collapse
ryselis profile image
Karolis Ryselis

Java var is nothing like Python's def. def is used to declare a function or method.

Collapse
javinpaul profile image
javinpaul Author

Yeah, that's true, Java var is less powerful than Python def or even JavaScript var but it still useful on making your code elegant and concise.

Collapse
javinpaul profile image
Collapse
diegopm profile image
Diego Pardo

Java does NOT have dynamic typing features, before or after java 10. var still is static typing.

Collapse
lluismf profile image