Comparison of Autoboxed Integer objects in JavaAutoboxing is a feature in Java that allows you to convert primitive types to their corresponding wrapper objects automatically. For example, the statement Integer x = 10; will automatically create an Integer object with the value 10 and assign it to the variable x. Here are some interesting output questions about the comparison of autoboxed Integer objects. Filename: AutoboxedExample1.java Output: Not Same Explanation: Because of autoboxing, the compiler automatically converts these primitive values to Integer objects. A and B reference two different Integer objects, even though they have the same value. The if statement in the program compares the references of the two objects. Because the references are different, the if statement will return false, and the message "Not Same" will be printed. Filename: AutoboxedExample2.java Output: Same Explanation: The a and b variables in the AutoboxedExample2 class will both refer to the same Integer object because the value 42 is within the range of -128 to 127, and the IntegerCache will return the corresponding object from the cache. It is why the if statement will return true, and the message "Same" will be printed. Filename: AutoboxedExample3.java Output: Not Same Explanation: A and b refer to two different objects, even though they have the same value. The if statement in the program compares the references of the two objects. Because the references are different, the if statement will return false, and the message "Not Same" will be printed. It is because the == operator in Java compares the references of two objects, not their values. To compare the values of two autoboxed Integer objects, you should use the compareTo() method. The compareTo() method will return 0 if the two objects have the same value, -1 if the first object is less than the second object, and 1 if the first object is greater than the second object. Filename: AutoboxedExample4.java Output: false Explanation: The object is created using the new operator, which refers to a newly created Integer object. The b object is created by autoboxing the value 5, meaning it refers to the same Integer object cached by the Integer class. Next TopicCount Tokens in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India