If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Auto-boxing and auto-unboxing are features introduced in Java to automatically convert between primitive data types and their corresponding wrapper classes seamlessly. These features simplify the code and make it more convenient to work with primitives and their wrapper objects. Auto-boxing allows you to convert a primitive data type to its wrapper class, and auto-unboxing does the reverse, converting a wrapper object to its corresponding primitive data type.
Example of auto-boxing:
javaCopy code
int number = 42; // primitive data type
Integer numberObj = number; // Auto-boxing: primitive to Integer (wrapper class)
Example of auto-unboxing:
javaCopy code
Integer ageObj = 25; // wrapper class object
int age = ageObj; // Auto-unboxing: Integer (wrapper class) to primitive int
Auto-boxing and auto-unboxing help simplify code and make it easier to work with collections that require objects (like ArrayList) or when using generics, which only work with reference types (objects).
Here's an example demonstrating the use of auto-boxing and auto-unboxing together:
javaCopy code
import java.util.ArrayList;
public class AutoBoxingUnboxingExample {
public static void main(String[] args) {
ArrayList<Integer> numbersList = new ArrayList<>();
// Auto-boxing: Adding primitive int values to the ArrayList
numbersList.add(10);
numbersList.add(20);
numbersList.add(30);
// Auto-unboxing: Retrieving primitive int values from the ArrayList and using them in calculations
int sum = numbersList.get(0) + numbersList.get(1) + numbersList.get(2);
System.out.println("Sum of elements in the ArrayList: " + sum);
}
}
In the example above, the ArrayList holds Integer objects, but we can add primitive int values directly to it due to auto-boxing. Similarly, when retrieving values from the ArrayList, auto-unboxing allows us to use them in calculations without explicitly converting them back to primitives.
Comments: 0