0Pricing
Java Academy · Lesson

Limitations of var

Where var cannot be used.

var Has Rules

var is convenient but limited. It works only for local variables with an initializer. Knowing where it cannot be used saves frustrating compile errors.

Locals Only

var is allowed only for local variables (inside methods, loops, etc.). The example below is valid because the variable is local.

public class Main {
    public static void main(String[] args) {
        var greeting = "OK for locals";
        System.out.println(greeting);
    }
}

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