Master Core Java Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Module 9

var and Local Variable Type Inference

Learn how Java uses the var keyword to simplify local variable declarations.

🔤

1. What is var?

Java introduced the var keyword in Java 10. It allows the compiler to infer the type of a local variable from the value assigned to it.

Instead of explicitly writing the type, you can use var. The compiler determines the actual type at compile time.

Java
var name = "Samadhan";
var age = 22;
var price = 99.99;
var active = true;
Important: var does not make Java dynamically typed. The variable still has a fixed type determined at compile time.

2. Explicit Type vs var

The traditional approach explicitly declares the variable type.

Java
String name = "Samiksha";
Integer age = 22;
Double salary = 50000.0;

The same declarations can be written using var.

Java
var name = "Sujit";
var age = 25;
var salary = 50000.0;

The compiler infers:

  • nameString
  • ageint
  • salarydouble

3. Compile-Time Type Inference

The type of a var variable is determined during compilation.

Java
var number = 100;

number = 200;

// number = "Java";  // Compile-time error
Remember: A variable declared with var cannot later be assigned a value of an incompatible type.

4. var Must Be Initialized

A var variable must have an initializer because the compiler needs the initializer to determine the variable's type.

Java
var name = "CIIT";

// var value;
// Invalid because the compiler cannot infer the type.

5. var Cannot Be Initialized with null Alone

The compiler cannot infer a type when the only initializer is null.

Java
// var value = null;
// Invalid because null does not provide enough type information.

Instead, provide an explicit reference type.

Java
String value = null;

6. var is Used for Local Variables

The var keyword is primarily used for local variables, including variables declared inside methods and loop variables.

Java
public class Simple {

    public static void main(String[] args) {

        var message = "Welcome CIIT Institute ❤️😍...!";

        System.out.println(message);
    }
}

7. var with Collections

var can make complex generic declarations easier to read.

Java
import java.util.ArrayList;
import java.util.List;

List<String> names =
    new ArrayList<>();

var names2 =
    new ArrayList<String>();

names2.add("Java");
names2.add("Spring");

The compiler knows that names2 is an ArrayList<String>.

8. var in Enhanced for Loop

var can also be used as the loop variable in an enhanced for loop.

Java
var names =
    List.of("Java", "Spring", "SQL");

for (var name : names) {
    System.out.println(name);
}

9. var in Traditional for Loop

The loop initialization section can also use var.

Java
for (var i = 0; i < 5; i++) {
    System.out.println(i);
}

10. var with try-with-resources

var can simplify local resource declarations when the resource type is obvious.

Java
import java.io.BufferedReader;
import java.io.FileReader;

try (var reader =
        new BufferedReader(
            new FileReader("data.txt")
        )) {

    String line = reader.readLine();

    System.out.println(line);
}

11. var and Lambda Expressions

A lambda expression normally requires a target functional-interface type. You cannot simply write var without a target type.

Java
var task = () -> {
    System.out.println("Running");
};

// Invalid because the compiler cannot infer
// a functional interface type from the lambda alone.

Use an explicit functional interface instead.

Java
Runnable task = () -> {
    System.out.println("Running");
};

task.run();

12. var Does Not Mean Object

var should not be confused with Object. The compiler still preserves the specific inferred type.

Java
var text = "Welcome CIIT 🌍";

System.out.println(
    text.length()
);

Here, text is inferred as String, so String methods can be used directly.

13. var with Diamond Operator

Java's diamond operator <> can be combined with var to reduce repetitive generic type declarations.

Java
var numbers =
    new ArrayList<Integer>();

numbers.add(10);
numbers.add(20);
numbers.add(30);

14. Readability

var can improve readability when the type is obvious from the right-hand side.

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

var data2 =
    new HashMap<String, List<Integer>>();
Good use: Use var when the initializer makes the type clear and the shorter declaration improves readability.

15. When Not to Use var

Avoid var when the inferred type is unclear or makes the code harder to understand.

Java
var result = getData();

If the return type of getData() is not obvious, an explicit type may be clearer.

Java
Customer result = getCustomer();

16. Advantages of var

  • Reduces repetitive type declarations.
  • Makes complex generic declarations shorter.
  • Can improve readability when the type is obvious.
  • Works with local variables.
  • Still provides compile-time type safety.

17. Limitations of var

  • Cannot be used for uninitialized local variables.
  • Cannot be initialized with only null.
  • Cannot be used directly for fields.
  • Cannot be used as a method parameter type.
  • Cannot be used as a method return type.
  • Cannot be used directly with an untyped lambda expression.

18. Complete Example

Java
import java.util.List;

public class Main {

    public static void main(String[] args) {

        var language = "Java";

        var version = 21;

        var frameworks =
            List.of(
                "Spring",
                "Spring Boot",
                "Hibernate"
            );

        System.out.println(
            "Language: " + language
        );

        System.out.println(
            "Version: " + version
        );

        for (var framework : frameworks) {

            System.out.println(
                framework
            );
        }
    }
}

19. Interview Questions

var is a local variable type-inference feature introduced in Java 10. The compiler determines the variable's type from its initializer.

No. Java remains statically typed. The variable type is inferred at compile time.

No. Java's var is intended for local variable declarations, not class fields.

No. The compiler needs an initializer to infer the variable type.

A bare var declaration cannot infer the target functional-interface type of a lambda expression.

Summary

In this lesson, you learned:

  • What var means in Java
  • Compile-time local variable type inference
  • How to use var with collections
  • Using var in loops
  • Using var with try-with-resources
  • Why var cannot be used with an untyped lambda
  • Advantages and limitations of var
  • When explicit types are clearer