0
0
JavaConceptBeginner · 3 min read

What is var in Java: Simple Explanation and Usage

var in Java is a keyword introduced in Java 10 that allows the compiler to infer the variable type automatically from the assigned value. It helps write cleaner code by avoiding explicit type declarations while keeping strong typing.
⚙️

How It Works

Imagine you want to tell a friend what kind of fruit you have, but instead of saying "apple" or "banana," you just show them the fruit. In Java, var works similarly by letting the computer figure out the type of a variable based on the value you give it. This means you don't have to write the type yourself; the compiler does it for you.

For example, if you write var number = 5;, Java understands that number is an integer because 5 is an integer. This makes your code shorter and easier to read, especially when the type is obvious from the value.

However, var is not a replacement for all variable declarations. It only works when the compiler can clearly see the type from the value you assign right away. Also, the variable still has a fixed type after that, so you can't change it later.

💻

Example

This example shows how to use var to declare variables without writing their types explicitly.

java
public class VarExample {
    public static void main(String[] args) {
        var message = "Hello, Java!";  // compiler infers String
        var count = 10;               // compiler infers int
        var price = 12.99;            // compiler infers double

        System.out.println(message);
        System.out.println(count);
        System.out.println(price);
    }
}
Output
Hello, Java! 10 12.99
🎯

When to Use

Use var when the type of a variable is clear from the value you assign, making your code cleaner and easier to read. It is especially helpful for long or complex types, like collections or generics, where writing the full type can be bulky.

For example, when working with lists or maps, var reduces clutter:

var list = new ArrayList<String>();

However, avoid using var when the type is not obvious, as it can make the code harder to understand. Also, var cannot be used for variables without an initial value or for method parameters.

Key Points

  • var lets Java infer variable types from assigned values.
  • It was introduced in Java 10 to simplify code.
  • Variables declared with var still have a fixed type after assignment.
  • Use it when the type is obvious to improve readability.
  • Cannot be used without initialization or for method parameters.

Key Takeaways

var allows automatic type inference for local variables in Java.
It makes code shorter and easier to read when the type is clear from the value.
var variables have fixed types determined at compile time.
Do not use var without initializing the variable.
Avoid var when the type is not obvious to keep code understandable.