DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech
  • Event-Driven Fractals
  • Easily Update and Reload SSL for a Server and an HTTP Client
  • How to Configure TLS/SSL With PEM Files

Trending

  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • 5 Subtle Indicators Your Development Environment Is Under Siege
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  1. DZone
  2. Coding
  3. Languages
  4. Finally, Java 10 Has var to Declare Local Variables

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.

By 
Javin Paul user avatar
Javin Paul
·
Mar. 29, 18 · Tutorial
Likes (36)
Comment
Save
Tweet
Share
173.8K Views

Join the DZone community and get the full member experience.

Join For Free

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 var, Scala 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.

Java (programming language) Scala (programming language)

Published at DZone with permission of Javin Paul, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech
  • Event-Driven Fractals
  • Easily Update and Reload SSL for a Server and an HTTP Client
  • How to Configure TLS/SSL With PEM Files

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!