Phase 2 of 20 · Topic 2.5

Type Inference with var (Java 10+)

1Concept

Java 10 introduced var for local variable type inference. The compiler infers the actual type statically at compile time based on the initializer expression. Type safety and performance are preserved 100%, without dynamic typing overhead.

2Architecture Diagram

Source Code:     var name = "Alice";  ---> Compiler (javac) infers String
Compiled Class: String name = "Alice";  ---> Identical Bytecode & Performance!

3Code Example

Core Java
import java.util.List;
import java.util.Map;

public class VarTypeInferenceDemo {
    public static void main(String[] args) {
        var username = "EnterpriseDev";
        var userCount = 42;
        var priceList = List.of(99.9, 149.5, 199.0);
        var userMap = Map.of(1, "Alice", 2, "Bob");

        System.out.println("Username Type: " + username.getClass().getSimpleName());
        System.out.println("User Count: " + userCount);
        System.out.println("Price List Count: " + priceList.size());
    }
}

4Expected Output

Username Type: String
User Count: 42
Price List Count: 3

5Key Takeaways

  • `var` can only be used for local variables with initializers; CANNOT be used for fields, parameters, or return types.
  • `var` is NOT dynamic typing like JavaScript; types are frozen at compile time.
  • Improves readability when dealing with long generic type signatures.