Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series — Extended Java Programming Java Tutorial Module 18 - Modern Java Features 8 to 21

Java 10 var Keyword for Local Variable Type Inference

Reviewed & accurate
AI Summary

Introduction

Java 10 shipped in March 2018 with the var keyword for local variable type inference, delivered through JEP 286. After more than two decades of explicitly typed local declarations like "BufferedReader br = new BufferedReader(...)", Java finally joined C++ (auto), C# (var), Go (:=), Scala (val and var), and Kotlin (val and var) in letting the compiler infer the type of a local variable from its initialiser. The change is syntactic, not semantic: the JVM bytecode is identical, and the type system is unchanged. What changes is the source-code ergonomics for long generic types.

For a Java learner, java 10 var keyword is the moment the language caught up with how developers actually write code. This post shows the syntax, the places where var is and is not allowed, the readability tradeoffs, and the rules that govern type inference in the presence of generics, lambdas, and null.

What is the Java 10 var Keyword?

The var keyword belongs to the family of type-inference features, alongside Java 7's diamond operator (new ArrayList<>()), Java 8 lambda parameter inference (e -> e.length()), and Java 14 switch expressions. var is not a keyword in the strict sense; it is a reserved type name, which means you can still use var as a variable name, method name, or package name in pre-Java 10 code. As of Java 10, you cannot use var as a class or interface name.

The crucial property is that var is compile-time only. The compiler substitutes the inferred type at the declaration site and emits the same bytecode as if you had written the type yourself. There is no runtime dynamic typing; once inferred, the type cannot change. The variable declared with var is statically typed, just like any other local variable. The compiler error you get from "var x = null;" is "variable initializer is 'null'" because the compiler cannot infer a type from a null literal alone.

How the var Keyword Works - Step by Step

Step 1: Write the declaration. Replace the explicit type with var on the left of the equal sign. The compiler inspects the initialiser expression on the right, computes its type, and assigns that type to the variable. For example, "var list = new ArrayList<String>();" produces a variable of type ArrayList<String>, exactly as if you had typed that.

Step 2: Check the constraints. var is allowed only on local variables in method, constructor, and lambda bodies; in for-loop and try-with-resources declarations; and in for-each loops. It is not allowed for fields, method parameters, catch clauses, constructor parameters, or return types. The compiler rejects every other use with a "var is not allowed in declaration" error.

Step 3: Inspect the inferred type. For "var x = new ArrayList<String>();", the inferred type is ArrayList<String>, not List<String>. The diamond infers the element type from the initialiser, and var infers the collection type from the new expression. To get a List type, you must write "List<String> list = new ArrayList<>();" the old way.

Step 4: Watch out for the null, lambdas, and array initialisers. "var x = null;" fails because null has no type. "var f = (a, b) -> a + b;" fails because a lambda needs a target type. "var a = {1, 2, 3};" fails because array initialisers need an explicit type. Each case requires you to either supply an explicit type or use a cast.

Step 5: Read the variable. The variable has the inferred type for the rest of the block, and every operation on it must be valid for that type. You cannot reassign a different-typed value: "var x = 5; x = "hello";" fails because the inferred type is int and String is not assignable.

Java Program for the var Keyword

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class VarKeywordDemo {

    static Map<String, Integer> buildIndex(List<String> words) {
        // (1) var inside a method body
        var index = new HashMap<String, Integer>();
        for (var i = 0; i < words.size(); i++) {  // (2) var in classic for
            var word = words.get(i).toLowerCase();  // (3) var inferred as String
            index.merge(word, 1, Integer::sum);
        }
        return index;
    }

    static Map<String, List<String>> groupByLength(List<String> words) {
        var grouped = words.stream()
                .collect(Collectors.groupingBy(String::length));
        return grouped;
    }

    public static void main(String[] args) {

        var names = List.of("Alice", "Bob", "Carol", "Dave", "Eve");
        System.out.println("(1) names inferred type: " + names.getClass().getName());

        // (2) Long generic types are the canonical use case
        var grouped = groupByLength(names);
        System.out.println("(2) grouped = " + grouped);

        // (3) try-with-resources with var
        try (var reader = new java.io.StringReader("hello");
             var br = new java.io.BufferedReader(reader)) {
            var line = br.readLine();
            System.out.println("(3) read line: " + line);
        } catch (java.io.IOException ex) {
            System.out.println("io error: " + ex.getMessage());
        }

        // (4) for-each with var
        var sb = new StringBuilder();
        for (var name : names) {
            sb.append(name).append(",");
        }
        System.out.println("(4) csv: " + sb.substring(0, sb.length() - 1));

        // (5) Inference narrows on new ArrayList<>() to ArrayList, not List
        var list = new ArrayList<String>();
        list.add("alpha");
        // list.add(42); // compile error - String only
        System.out.println("(5) list class = " + list.getClass().getName());

        // (6) Generic inference with lambda target typing
        java.util.function.Function<String, Integer> lenFn = String::length;
        var result = lenFn.apply("imcseian");
        System.out.println("(6) length of imcseian = " + result);

        // (7) Inference with stream collectors
        var byLength = names.stream()
                .collect(Collectors.groupingBy(String::length));
        System.out.println("(7) byLength = " + byLength);

        // (8) Local lambda with explicit param types is rare; target-typed
        java.util.function.Function<Integer, Integer> square = x -> x * x;
        var squared = square.apply(7);
        System.out.println("(8) square(7) = " + squared);

        // (9) Trivial inference in a simple arithmetic expression
        var sum = 0;
        for (var i = 1; i <= 5; i++) {
            sum += i;
        }
        System.out.println("(9) sum 1..5 = " + sum);

        // (10) Mistakes that the compiler rejects:
        // var nothing = null;            // ERROR: cannot infer
        // var lambda = (a, b) -> a + b;  // ERROR: lambda needs target type
        // var arr = {1, 2, 3};           // ERROR: array init needs type
        // var f = () -> "hi";            // ERROR: lambda needs target type
        System.out.println("(10) compile-time-only: var does not exist at runtime");
    }
}

Code Explanation - Line by Line

The buildIndex method uses var in three places. First, the local "var index = new HashMap<String, Integer>();" declares index as HashMap<String, Integer>, the type of the new expression. The diamond operator <String, Integer> supplies the type arguments; var infers the collection class. Second, the classic for-loop uses "var i = 0" because Java 10 allows var in the initialiser of a classic for. Third, "var word = words.get(i).toLowerCase();" infers word as String because the expression on the right has compile-time type String.

The groupByLength method uses var on the result of a stream collect call. The expression Collectors.groupingBy(String::length) returns a Collector whose type is Collector<String, ?, Map<String, List<String>>>, and the collect call returns Map<String, List<String>>. Writing var grouped means you do not have to spell out the four-level generic type. This is the canonical readability win of var.

In the main method, section (1) declares names with var; the inferred type is the immutable List returned by List.of, which at runtime is List<String> backed by an internal ImmutableCollections class. The getClass call on the runtime object confirms this. Section (2) shows the result of groupByLength grouped by string length, with names of the same length collected together.

Section (3) demonstrates try-with-resources with var. Before Java 10, every resource variable had to declare its type explicitly; with Java 10, you can write "try (var reader = new StringReader("hello"))" and let the compiler infer the type. Section (4) shows for-each with var, where the loop variable name is declared as var and the compiler infers its type from the iteration target, here String from List<String>.

Section (5) is the most subtle. "var list = new ArrayList<String>();" infers list as ArrayList<String>, not as List<String>. The diamond supplies the type argument, but var only sees the new expression's type. That means you can call any ArrayList-specific method like trimToSize on list, and you cannot reassign list to a LinkedList. If you want the wider List type, write "List<String> list = new ArrayList<>();" the old way.

Section (6) shows that var works fine when the initialiser is a method call on a typed variable: lenFn has explicit type Function<String, Integer>, and the result is inferred to Integer. Section (7) shows the same grouped-by-length idiom in the main method. Section (8) shows a lambda assigned to an explicitly typed variable, then var on the result. Section (9) shows that var with an int initialiser produces an int variable, and the for-loop sum works exactly as if you had written "int sum = 0".

Section (10) documents the four kinds of declarations that the compiler rejects. "var nothing = null;" fails because the null literal has no type. A lambda like "(a, b) -> a + b" cannot be assigned to var because the compiler needs a target type to infer the parameter and return types of a lambda. An array initialiser "{1, 2, 3}" cannot be assigned to var because it requires an explicit component type. A zero-argument lambda "var f = () -> "hi"" also fails for the same reason as (a, b) -> a + b.

Sample Input and Output

(1) names inferred type: java.util.ImmutableCollections$ListN
(2) grouped = {3=[Bob, Eve], 4=[Dave], 5=[Alice, Carol]}
(3) read line: hello
(4) csv: Alice,Bob,Carol,Dave,Eve
(5) list class = java.util.ArrayList
(6) length of imcseian = 8
(7) byLength = {3=[Bob, Eve], 4=[Dave], 5=[Alice, Carol]}
(8) square(7) = 49
(9) sum 1..5 = 15
(10) compile-time-only: var does not exist at runtime

The output confirms every inference rule. The runtime class of names is the internal ImmutableCollections.ListN, which is what List.of produces. The grouped map shows names clustered by string length: Bob and Eve both have length 3, Dave has length 4, Alice and Carol have length 5. The BufferedReader reads the StringReader's content. The CSV joins all five names with commas. The inferred list class is ArrayList, not List. The lambda on lenFn produces the integer length of "imcseian", which is 8 characters. The same grouping by length applied in main produces the same result as in the helper method. The square lambda produces 49 for input 7. The for-loop sum produces 15. Section (10) prints the documentation string; the actual compile-time errors are described in the comments.

Common Mistakes to Avoid

The first mistake is treating var as dynamic typing. The variable has the inferred type for its entire scope, and reassignment to a different type fails at compile time. The second mistake is using var where the inferred type is too narrow, such as "var list = new ArrayList<String>();" when you need to expose the wider List contract. In that case write "List<String> list = new ArrayList<>();" explicitly to upcast at the declaration.

The third mistake is using var for "var x = 5;" where the inferred type is int but you wanted long. The fix is to write "var x = 5L;" so the literal has the right type. The same applies to "var d = 1.5;" where the inferred type is double but you wanted float; write "var f = 1.5f;" instead. The fourth mistake is using var when the initialiser returns null because the null type cannot be inferred; the compiler rejects the declaration.

The fifth mistake is overusing var on local declarations where the type adds information. For example, "var data = service.getData();" hides the return type, which may make the next line harder to read because you cannot tell what methods are available on data. The Java style guidelines recommend var when the type is obvious from the initialiser (such as a new expression or a static factory) and an explicit type when the type is not obvious. The sixth mistake is using var for fields, method parameters, or catch clauses; the compiler rejects all of these with "var is not allowed here".

The seventh mistake is assuming var is a reserved keyword. It is a reserved type name, which means you can still use var as a variable name. For example, "int var = 5;" is legal, and "var var = 5;" is also legal (with var both as the type and the variable name). This is by design to preserve backwards compatibility with pre-Java 10 code that used var as an identifier.

Real-World Applications

The var keyword is now standard in every modern Java codebase. The Spring Framework 5+ source uses var widely for stream intermediate variables; Spring Boot's @Bean method bodies use var for the local declarations of configured beans. The Apache Commons Lang, JUnit 5, and Mockito source code all use var after their Java 9 baseline adoption. The JDK itself uses var internally in the implementation of Stream, Collectors, and the Java 11 HttpClient.

In the wider ecosystem, IntelliJ IDEA ships an "introduce var" intention that converts a long explicit type to var when the inferred type is obvious. The Eclipse compiler and the OpenJDK jcstress use var in their own test code. Kotlin's val and var are still more concise because they handle the var-vs-val distinction automatically, but the Java var keyword is the equivalent feature for Java source readability. Studying java 10 var keyword is therefore the entry ticket to reading any modern Java library source and to understanding the type-inference features that ship in Java 14 switch expressions and Java 22 pattern matching. The java 10 var keyword is also a compile-time-only feature, so existing bytecode and tooling are unaffected.

Conclusion

We showed the syntax for var, the rules that govern where it is and is not allowed, the inference pitfalls around null, lambdas, array initialisers, and the choice between var and explicit types when the type information is not obvious. var is a pure syntactic convenience that does not change the runtime behaviour of the compiled code, and it is the standard idiom for declaring local variables in every modern Java source file. The natural next topics to study are the Java 10 List.copyOf, Set.copyOf, and Map.copyOf methods that pair with var for concise immutable-collection code, and the Java 14 switch expressions that build on the same type-inference machinery.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments