Java var Keyword Example

1. Introduction

In this blog post, we'll explore the var keyword in Java. Introduced in Java 10, var is used for local variable type inference, allowing the compiler to infer the type of a variable from its initializer expression.

Definition

The var keyword in Java is used to declare local variables without explicitly stating their type. The type of these variables is inferred by the compiler based on the context in which they are used. This feature simplifies the code and makes it more readable, especially in cases with complex generic types.

2. Program Steps

1. Declare variables using the var keyword.

2. Initialize these variables with different types of data.

3. Use these variables in various operations to demonstrate type inference.

3. Code Program

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

public class VarKeywordExample {
    public static void main(String[] args) {
        // Using var with primitive types
        var number = 10; // inferred as int
        var message = "Hello Java"; // inferred as String

        // Using var with object types
        var list = new ArrayList<String>(); // inferred as ArrayList<String>
        list.add("Apple");
        list.add("Banana");

        // Using var in a loop
        for (var item : list) {
            System.out.println(item); // item is inferred as String
        }

        // Using var with lambda expression
        var thread = new Thread(() -> System.out.println("Thread running"));
        thread.start();
    }
}

Output:

Apple
Banana
Thread running

Explanation:

1. number and message are declared using var. Their types are inferred as int and String respectively, based on the assigned values.

2. list is initialized as a new ArrayList<String> and is inferred as such. Items are added to the list and printed using a for-each loop.

3. In the for-each loop, item is declared using var and its type is inferred as String, which is the type of elements in list.

4. A Thread object is created with a lambda expression. The var keyword is used to infer the Thread type.

5. The output demonstrates that var correctly infers the type of each variable, simplifying the code without compromising its readability and functionality.


Comments