The var Keyword

2 min read ·

The var keyword was introduced in Java 10.
It allows local variable type inference.

What is var

With var, Java automatically detects the variable type based on the assigned value.
Java infers:
  • number → int
  • name → String
  • price → double

Rules of Using var

  • Can only be used for local variables
  • Must initialize at the time of declaration
  • Cannot be used for instance variables
  • Cannot be null without type context
Correct:
Incorrect:
Compilation error because no initialization.

Limitations of var

  • Cannot change type later
  • Reduces readability if used excessively
  • Cannot be used without assignment
Example:
Type remains int.

var with Different Data Types

Java determines the type at compile time.

These topics complete the advanced understanding of Java data types and memory behavior.