Java var Keyword: Type Inference, Syntax, Examples & Best Practices

0

The var keyword allows Java to infer the type of a local variable from the value assigned to it. Instead of explicitly writing the data type, you write var, and the compiler determines the variable's type from its initializer.

The important point is that var does not make Java dynamically typed. Java still knows the variable's type at compile time. You are simply allowing the compiler to infer that type for you.

Why Was var Introduced?

Java traditionally requires developers to write the data type explicitly.

String studentName = "Rahul";
int studentAge = 20;
double studentMarks = 85.5;

With var, the same declarations can be written more compactly:

var studentName = "Rahul";
var studentAge = 20;
var studentMarks = 85.5;

The compiler determines that studentName is a String, studentAge is an int, and studentMarks is a double.

Important: var does not mean "any type." It means Java will infer the specific type from the initializer.

Basic Syntax

The basic syntax is:

var variableName = value;

For example:

var name = "Bibhu";
var age = 25;
var salary = 35000.50;
var active = true;

Java infers the types as String, int, double, and boolean respectively.

var Is Statically Typed

One of the most common beginner mistakes is thinking that var makes Java behave like a dynamically typed language. It does not.

var age = 25;

age = 30;

// age = "Twenty Five";  // Compilation error

The compiler has already inferred that age is an int. Therefore, assigning a String later is not allowed.

The type is inferred once at compile time; it does not change while the program is running.

var Must Have an Initializer

Java needs a value from which it can determine the variable's type. Therefore, you cannot declare a local variable using var without initializing it.

var age;

This code does not compile because Java has no value from which it can infer the type of age.

Instead, provide an initializer:

var age = 25;

var Can Be Used for Local Variables

The var keyword is primarily intended for local variable declarations.

public class Main {

    public static void main(String[] args) {

        var name = "Rahul";
        var age = 20;

        System.out.println(name);
        System.out.println(age);
    }
}

Here, both variables are local variables inside the main() method, so var can be used.

var Cannot Be Used for Instance Variables

You cannot declare an instance variable using var.

public class Student {

    var name = "Rahul";
}

This is invalid Java. Instance variables must have an explicit declared type.

Write it like this instead:

public class Student {

    String name = "Rahul";
}

var Cannot Be Used for Static Variables

The same rule applies to static variables.

public class Student {

    static var school = "ABC School";
}

This is not valid because var cannot be used for class fields.

var with Objects

One useful situation for var is when the right side of an expression already clearly shows the type.

var student = new Student("Rahul", 20);

The compiler can infer that student is a Student reference because the initializer creates a Student object.

Without var, you would normally write:

Student student = new Student("Rahul", 20);

Both versions are statically typed. The difference is that the first version asks the compiler to infer the declared type.

var with Collections

The keyword can make declarations involving generic collections shorter.

var students = new ArrayList<String>();

students.add("Rahul");
students.add("Anita");

The compiler can infer the variable's type from the initializer. This can improve readability when the declared type would otherwise be long and repetitive.

var and Generics

Consider a declaration with a more complicated generic type:

Map<String, List<Integer>> studentMarks =
        new HashMap<String, List<Integer>>();

Using var can reduce the repetition:

var studentMarks =
        new HashMap<String, List<Integer>>();

This can make some declarations easier to read, particularly when the initializer already communicates the type clearly.

var with Loops

The var keyword can also be used for local loop variables.

for (var i = 1; i <= 5; i++) {

    System.out.println(i);
}

The compiler infers i as an int from the initializer.

var with Enhanced for Loops

It can also be used with enhanced for loops.

var students = new String[] {"Rahul", "Anita", "Amit"};

for (var student : students) {

    System.out.println(student);
}

The loop variable's type is inferred from the elements of the array.

var Cannot Be Initialized with null Alone

A standalone null value does not provide enough type information for the compiler to infer a type.

var name = null;

This is invalid because Java cannot determine whether name should be a String, Student, List, or some other reference type.

With an actual object initializer, the compiler has enough information:

var name = "Rahul";

var Does Not Mean Object

Another common misunderstanding is that var is equivalent to the Object type. It is not.

var age = 25;

This does not mean that age is declared as Object. The compiler infers the specific type int.

Declaration Actual Type
var age = 25; int
var price = 25.5; double
var name = "Rahul"; String
var active = true; boolean
var student = new Student(); Student

var vs Explicit Type

Explicit Type var
int age = 25; var age = 25;
String name = "Rahul"; var name = "Rahul";
Student student = new Student(); var student = new Student();
Type is written by the developer. Type is inferred by the compiler.
Can be used for fields. Cannot be used for instance or static fields.

When Should You Use var?

The best use of var is when the initializer makes the type obvious and removing the explicit type improves readability.

var student = new Student("Rahul", 20);

The type is easy to understand because the initializer clearly says new Student.

However, if removing the type makes the code harder to understand, explicitly writing the type may be better.

When Should You Avoid var?

Avoid using var simply to reduce the number of characters. Readability should be the deciding factor.

var result = calculate();

If the return type of calculate() is not obvious and understanding it requires jumping to another part of the application, an explicit type may sometimes communicate the intent more clearly.

Common Beginner Mistakes

  • Thinking var makes Java dynamically typed.
  • Trying to declare a var variable without an initializer.
  • Trying to use var for instance or static variables.
  • Assuming var means Object.
  • Using var everywhere even when the explicit type makes the code easier to understand.

Best Practices

Use var when the initializer makes the inferred type obvious and the shorter declaration improves readability. Do not use it merely because the syntax is shorter.

var student = new Student("Rahul", 20);
var total = price * quantity;

Both declarations are easy to understand because the expressions provide useful clues about the inferred types.

Interview Insight

If an interviewer asks, "What is var in Java?", a strong answer is: var is a local variable type-inference feature introduced in Java 10. The compiler determines the variable's static type from its initializer. It does not make Java dynamically typed.

A common follow-up is, "Can var be used for instance variables?" The answer is no. Java's var is intended for local variable type inference, including local variables, loop variables, and resource variables in applicable contexts.

Quick Revision

Concept Key Point
var Allows Java to infer the type of a local variable from its initializer.
Typing Java remains statically typed; var does not create dynamic typing.
Initializer Required because Java needs it to infer the variable's type.
Local Variables Primary use of var.
Fields var cannot be used for instance or static fields.
null var cannot infer a type from a standalone null value.
Best Practice Use var when type inference makes the code clearer, not merely shorter.

The var keyword is best understood as a convenience for local variable declarations, not as a change to Java's type system. Java still determines the variable's type at compile time. Once you understand that distinction, you can use var confidently without losing the safety and clarity of Java's static typing.

Post a Comment

0Comments
Post a Comment (0)