Var Keyword

Introduction

The var keyword (introduced in Java 10) allows type inference for local variables. The compiler automatically determines the type from the assigned value.


Basic Syntax

Without var:

String name = "John";
int age = 25;
double salary = 50000.0;
ArrayList<String> list = new ArrayList<String>();

With var:

var name = "John";              // String
var age = 25;                   // int
var salary = 50000.0;           // double
var list = new ArrayList<String>();  // ArrayList<String>

Examples

Simple Types:

var num = 100;          // int
var price = 99.99;      // double
var letter = 'A';       // char
var flag = true;        // boolean
var text = "Hello";     // String

System.out.println(num);    // 100
System.out.println(price);  // 99.99

Objects:

var student = new Student("John", 101);
var list = new ArrayList<Integer>();
var map = new HashMap<String, Integer>();

list.add(10);
list.add(20);
System.out.println(list);  // [10, 20]

Arrays:

var numbers = new int[]{1, 2, 3, 4, 5};
var names = new String[]{"John", "Alice", "Bob"};

for (var num : numbers) {
    System.out.println(num);
}

Where var Can Be Used

1. Local Variables:

public void method() {
    var x = 10;           // ✓ OK
    var name = "John";    // ✓ OK
}

2. For Loop:

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

3. Enhanced For Loop:

var list = List.of("A", "B", "C");
for (var item : list) {
    System.out.println(item);
}

4. Try-with-Resources:

try (var reader = new BufferedReader(new FileReader("file.txt"))) {
    var line = reader.readLine();
    System.out.println(line);
}

Where var CANNOT Be Used

1. Fields (Instance Variables):

class Student {
    var name = "John";  // ❌ Error
    var age = 20;       // ❌ Error
}

2. Method Parameters:

public void display(var name) {  // ❌ Error
    System.out.println(name);
}

3. Method Return Type:

public var getValue() {  // ❌ Error
    return 100;
}

4. Without Initialization:

var x;           // ❌ Error
x = 10;

var y = null;    // ❌ Error (cannot infer type)

Rules for var

  1. Must initialize at declaration
  2. Cannot be null (cannot infer type)
  3. Only for local variables
  4. Type inferred from right side
  5. Cannot change type later

Examples with Restrictions

Must Initialize:

var x = 10;      // ✓ OK
var y;           // ❌ Error
y = 20;

Cannot Be Null:

var name = "John";      // ✓ OK
var value = null;       // ❌ Error (type unknown)
var obj = new Object(); // ✓ OK

Type Cannot Change:

var num = 10;    // int
num = 20;        // ✓ OK (still int)
num = "Hello";   // ❌ Error (cannot change to String)

Practical Examples

Example 1: Simple Usage

public class VarExample {
    public static void main(String[] args) {
        var message = "Hello, World!";
        var count = 5;
        var price = 99.99;

        System.out.println(message);
        System.out.println("Count: " + count);
        System.out.println("Price: " + price);
    }
}

Example 2: With Collections

import java.util.*;

public class CollectionExample {
    public static void main(String[] args) {
        var list = new ArrayList<String>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        for (var fruit : list) {
            System.out.println(fruit);
        }

        var map = new HashMap<String, Integer>();
        map.put("John", 25);
        map.put("Alice", 30);

        for (var entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Example 3: Loop Variables

public class LoopExample {
    public static void main(String[] args) {
        // Traditional for loop
        for (var i = 0; i < 5; i++) {
            System.out.println(i);
        }

        // Enhanced for loop
        var numbers = new int[]{10, 20, 30, 40, 50};
        for (var num : numbers) {
            System.out.println(num);
        }
    }
}

Benefits of var

  1. Less Verbose: Shorter code
  2. Readable: Focus on logic, not types
  3. Convenience: Especially with long type names

Long Type Names:

// Without var
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

// With var
var map = new HashMap<String, List<Integer>>();

When to Use var

Good Use:

var list = new ArrayList<String>();  // Type obvious
var student = new Student("John");   // Clear from context
var reader = new BufferedReader(...); // Long type name

Avoid When Unclear:

var x = getValue();  // What type is returned?
var data = process();  // Not clear

var vs Explicit Type

FeaturevarExplicit Type
Syntaxvar x = 10;int x = 10;
Type SafetyCompile-timeCompile-time
ReadabilitySometimes less clearAlways clear
FlexibilityOnly local variablesAnywhere
SinceJava 10Always

Important Points

  1. Not a new type, just type inference
  2. Type determined at compile time
  3. Still strongly typed (not dynamic)
  4. Cannot change type after declaration
  5. Only local variables, not fields

Quick Reference

// Valid
var num = 10;
var text = "Hello";
var list = new ArrayList<String>();
for (var i = 0; i < 5; i++) { }
for (var item : list) { }

// Invalid
var x;                    // ❌ No initialization
var y = null;             // ❌ Cannot infer
class Test { var f = 1; } // ❌ Not for fields
void method(var p) { }    // ❌ Not for parameters
var getValue() { }        // ❌ Not for return type

Exam Tips

Remember:

  1. var = type inference (Java 10+)
  2. Must initialize at declaration
  3. Only for local variables
  4. Cannot use for fields, parameters, return types
  5. Cannot be null
  6. Type cannot change
  7. Still strongly typed
  8. Type inferred at compile time

Common Questions:

  • What is var keyword?
  • Where can var be used?
  • Where var cannot be used?
  • Can var be null?
  • Is var dynamically typed?
  • Difference between var and explicit type?