Java Autoboxing

Java Autoboxing

Autoboxing in Java is the process of automatically converting a primitive type to its corresponding wrapper class when it is needed. For example, when you assign an int value to a Integer object, the int value is automatically boxed (converted) to an Integer object. This process is called autoboxing.

Here is an example of autoboxing in action:

int x = 10;
Integer y = x;  // autoboxing
Sou‮‬rce:www.lautturi.com

In this example, the int value 10 is assigned to the Integer object y. The int value is automatically boxed to an Integer object using the Integer class's valueOf() method.

Autoboxing is useful because it allows you to use primitive types and wrapper classes interchangeably in your code. You can pass a primitive type as an argument to a method that expects a wrapper class, and vice versa.

Here is an example of using autoboxing to pass a primitive type as an argument to a method that expects a wrapper class:

import java.util.ArrayList;

public class AutoboxingExample {

    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);  // autoboxing
        numbers.add(20);  // autoboxing
        numbers.add(30);  // autoboxing

        int sum = sum(numbers);
        System.out.println(sum);  // 60
    }

    public static int sum(ArrayList<Integer> numbers) {
        int result = 0;
        for (int number : numbers) {
            result += number;  // unboxing
        }
        return result;
    }
}

In this example, the main() method creates an ArrayList of Integer objects and adds some int values to it using the add() method. The int values are automatically boxed to Integer objects using autoboxing.

The sum() method takes an ArrayList of Integer objects as an argument and sums the elements of the list using a for-each loop. In the loop, the number variable is an int, so the Integer objects in the list are automatically unboxed (converted) to int values using the intValue() method of the Integer class.

Autoboxing and unboxing are convenient features of Java, but they can have a performance impact if used excessively. To avoid unnecessary boxing and unboxing, it is recommended to use primitive types whenever possible and to use wrapper classes only when necessary.

Created Time:2017-11-03 00:14:37  Author:lautturi