Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

Normally you write ArrayList<String> list = new ArrayList<String>() — you write the type TWICE. With var, Java looks at the right side and figures out the type automatically. You just write var list = new ArrayList<String>(). Less typing, same result.

Real World Analogy

Ordering food at a restaurant. Normally you say "I want one plate of biryani." With var it's like pointing at the menu and saying "I want THAT." The waiter (Java compiler) knows exactly what you mean.

What is var?

var is a local variable type inference keyword introduced in Java 10. The compiler automatically infers the type from the right-hand side expression.
java
QUBITS OF DPK
1// Before Java 10
2ArrayList<String> names = new ArrayList<String>();
3HashMap<String, Integer> scores = new HashMap<String, Integer>();
4BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
5
6// Java 10+ with var
7var names   = new ArrayList<String>();
8var scores  = new HashMap<String, Integer>();
9var reader  = new BufferedReader(new FileReader("file.txt"));

var in Loops

java
QUBITS OF DPK
1var numbers = List.of(1, 2, 3, 4, 5);
2
3// for-each with var
4for (var number : numbers) {
5    System.out.println(number);
6}
7
8// traditional for with var
9for (var i = 0; i < numbers.size(); i++) {
10    System.out.println(numbers.get(i));
11}

How var Works Under the Hood

var is resolved entirely at compile time. It is NOT dynamic typing like Python/JavaScript.
java
QUBITS OF DPK
1var x = 10;          // compiler sees: x is int
2var name = "Deepak"; // compiler sees: name is String
3var list = new ArrayList<String>(); // compiler sees: list is ArrayList<String>
4
5// After compilation, bytecode is IDENTICAL to explicit types
6// var has ZERO runtime overhead

Where var CANNOT Be Used

java
QUBITS OF DPK
1// 1. Class fields
2class Car {
3    var speed = 100;    // ❌ compile error! Only local variables
4}
5
6// 2. Method parameters
7void process(var input) { }  // ❌ compile error!
8
9// 3. Method return type
10var getName() { }    // ❌ compile error!
11
12// 4. Without initialization
13var x;               // ❌ compiler can't infer type
14
15// 5. Null initialization
16var obj = null;      // ❌ can't infer type from null
17
18// 6. Lambda expressions
19var func = () -> System.out.println("hi");  // ❌ can't infer functional interface
20
21// 7. Array initializer shorthand
22var arr = {1, 2, 3}; // ❌ must use: var arr = new int[]{1, 2, 3};

Where var CAN Be Used

java
QUBITS OF DPK
1// Local variables only
2void method() {
3    var count = 0;                              // ✅ int
4    var name = "Deepak";                        // ✅ String
5    var list = new ArrayList<String>();         // ✅ ArrayList<String>
6    var map  = new HashMap<String, Integer>();  // ✅ HashMap<String, Integer>
7    var arr  = new int[]{1, 2, 3};             // ✅ int[]
8}
9
10// try-with-resources
11try (var reader = new BufferedReader(new FileReader("file.txt"))) {
12    var line = reader.readLine();   // ✅
13}
14
15// for loops
16for (var i = 0; i < 10; i++) { }  // ✅
17for (var item : list) { }          // ✅

var is NOT a Keyword (Technically!)

java
QUBITS OF DPK
1// var is a reserved type name, not a keyword
2// This means you can still use 'var' as a variable name! (bad practice)
3int var = 10;   // ✅ compiles! (but horrible practice, never do this)
4
5// But you cannot use it as a class name in new code

Production Use Cases

java
QUBITS OF DPK
1// Clean code with complex generics
2var usersByCity = new HashMap<String, List<User>>();
3// vs
4HashMap<String, List<User>> usersByCity = new HashMap<String, List<User>>();
5
6// Stream pipelines
7var result = users.stream()
8    .filter(u -> u.getAge() > 18)
9    .collect(Collectors.toList());
10
11// try-with-resources
12try (var conn = dataSource.getConnection();
13     var stmt = conn.prepareStatement(sql)) {
14    // clean, readable
15}

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — Readability can suffer
2var x = getValue();   // ⚠️ what type is x? Hard to tell without IDE
3// Better: use var only when type is obvious from RHS
4
5// Trap 2 — var infers most specific type
6var list = new ArrayList<String>();
7// Type is ArrayList<String>, NOT List<String>
8// May cause issues if you need to switch implementation
9// Better practice: List<String> list = new ArrayList<>();
10
11// Trap 3 — Cannot use var for fields
12class Car { var speed = 100; }  // ❌
13
14// Trap 4 — var is compile-time, NOT runtime dynamic typing
15var x = 10;
16x = "hello";  // ❌ compile error! x is int, can't assign String

30-Second Interview Answer

"var is local variable type inference introduced in Java 10. The compiler infers the type from the right-hand side at compile time — it is NOT dynamic typing, the bytecode is identical to explicit types with zero runtime overhead. var can only be used for local variables, loop variables, and try-with-resources — NOT for fields, parameters, or return types. Key trap: var infers the most specific type, so var list = new ArrayList<>() gives ArrayList not List, which can hurt flexibility."

Interview Questions & MAANG-Level Answers

Q1. What is var in Java and when was it introduced?
var is local variable type inference introduced in Java 10 (JEP 286). The compiler infers the variable's type from the right-hand side expression at compile time. var names = new ArrayList<String>() — compiler infers names is ArrayList<String>. The bytecode is identical to writing the explicit type — zero runtime overhead, same performance.
Q2. Is var dynamic typing like Python? Explain.
No, absolutely not. var is compile-time type inference — the type is fixed at compilation and cannot change. var x = 10 makes x an int forever — x = "hello" is a compile error. Python's dynamic typing allows a variable to hold any type at runtime. Java remains statically typed — var just lets the compiler write the type for you when it can be unambiguously inferred. Think of it as "the compiler fills in the type" not "the type is flexible".
Q3. Where can and cannot var be used?
Can: local variables with initialization, for loop variables (for (var i = 0; i < 10; i++)), for-each variables (for (var item : list)), try-with-resources (try (var conn = getConn())). Cannot: class fields, method parameters, method return types, variables without initialization (var x;), null initialization (var x = null), lambda parameters (sort of — Java 11 allows (var x, var y) -> x + y in lambdas), array shorthand (var arr = {1,2,3} is invalid).
Q4. What is the difference between var list = new ArrayList<String>() and List<String> list = new ArrayList<>()?
With var list = new ArrayList<String>(), the inferred type is ArrayList<String> — the most specific concrete type. With List<String> list = new ArrayList<>(), the declared type is List<String> — the interface. The second form is better practice: if you later change to LinkedList, only the right side changes. With var, if you accidentally call ArrayList-specific methods, switching implementation later breaks code. Program to interfaces, not implementations — prefer explicit interface types over var for collection declarations.
Q5. Is var a keyword in Java?
Technically NO — var is a reserved type name, not a keyword. This means you can still use var as a variable or method name (though you shouldn't): int var = 10 compiles without error. You cannot use it as a class name in new code. This design was intentional for backward compatibility — existing code that used var as a variable name would still compile after Java 10.