AI Hints
Home›Java Tutorial›Optional, var and Pattern Matching
Java · Lesson 107 of 120

var

Let Java work out the type.

⏱ 2 min read▶ Video at 2:16:50🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Some types are long to write, again and again. With var, Java works out the type of a local variable for you, from its value.

  • Long type names
  • var
  • Java works it out

Using var

Var count holds ten, so count is an int. Var name is a String. Var saves a lot of typing, with long types like this map. It works in for each loops too. But the type is still fixed. Run it. The map prints fine. But putting text into count fails, because count is still an int.

Main.javajava
import java.util.*;
public class Main {
    public static void main(String[] args) {
        var count = 10;
        var name = "Java";
        var prices = new HashMap<String, List<Double>>();
        prices.put("tea", List.of(2.5, 2.8));
        for (var entry : prices.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
        System.out.println(name + " " + (count + 1));
        count = "eleven";
    }
}
Output
Main.java:12: error: incompatible types: String cannot be converted to int
        count = "eleven";
                ^
1 error
error: compilation failed

When to use var

Var only works for local variables that are given a value straight away. It doesn't make Java loose, the type is still checked. Use it when the type is obvious from the right side. Write the type when it helps the reader.

keyvalue
Works forlocal variables
Needsa starting value
Stillstrongly typed
Use whenthe type is obvious

Summary

Var lets Java work out a local variable's type. The type is still fixed, and still checked. Next, pattern matching.

Key takeaways
  • var x = …
  • Local variables only
  • Still type-checked
Next up: Pattern Matching — test and unpack in one step