0Pricing
Java Academy · Lesson

Using var for Locals

Let the compiler infer the type.

Local Type Inference

Since Java 10, you can declare local variables with var and let the compiler infer the type from the initializer. This is local type inference. The variable is still strongly typed.

Your First var

Replace an explicit type with var when assigning a value. The compiler sees the literal and infers the right type.

public class Main {
    public static void main(String[] args) {
        var message = "Hello";
        var count = 42;
        System.out.println(message + " " + count);
    }
}

All lessons in this course

  1. Using var for Locals
  2. When var Helps Readability
  3. var in for Loops
  4. Limitations of var
← Back to Java Academy