40 lines
1.3 KiB
Java
40 lines
1.3 KiB
Java
|
public class AutoBoxUnBoxDemo {
|
||
|
public static void main(String[] args) {
|
||
|
// Autoboxing examples
|
||
|
Integer intObj = 10;
|
||
|
Double doubleObj = 3.14;
|
||
|
Character charObj = 'A';
|
||
|
Boolean boolObj = true;
|
||
|
|
||
|
System.out.println("Autoboxing examples:");
|
||
|
System.out.println("Integer: " + intObj);
|
||
|
System.out.println("Double: " + doubleObj);
|
||
|
System.out.println("Character: " + charObj);
|
||
|
System.out.println("Boolean: " + boolObj);
|
||
|
|
||
|
// Unboxing examples
|
||
|
int intValue = intObj;
|
||
|
double doubleValue = doubleObj;
|
||
|
char charValue = charObj;
|
||
|
boolean boolValue = boolObj;
|
||
|
|
||
|
System.out.println("\nUnboxing examples:");
|
||
|
System.out.println("int: " + intValue);
|
||
|
System.out.println("double: " + doubleValue);
|
||
|
System.out.println("char: " + charValue);
|
||
|
System.out.println("boolean: " + boolValue);
|
||
|
|
||
|
// Demonstrating autoboxing in method calls
|
||
|
printObject(50); // autoboxing int to Integer
|
||
|
|
||
|
// Demonstrating unboxing in expressions
|
||
|
Integer sum = intObj + 5; // unboxing for addition, then autoboxing result
|
||
|
System.out.println("\nSum after unboxing and autoboxing: " + sum);
|
||
|
}
|
||
|
|
||
|
public static void printObject(Object obj) {
|
||
|
System.out.println("\nObject passed: " + obj);
|
||
|
}
|
||
|
}
|
||
|
|