When we assign an integer value to an Integer object, the value is autoboxed into an Integer object. For example the statement “Integer x = 10” creates an object ‘x’ with value 10.
Following are some interesting output questions based on comparison of Autoboxed Integer objects.
Predict the output of following Java Program
Since x and y refer to different objects, we get the output as “Not Same”
The output of following program is a surprise from Java.
In Java, values from -128 to 127 are cached, so the same objects are returned. The implementation of valueOf() uses cached objects if the value is between -128 to 127.
If we explicitly create Integer objects using new operator, we get the output as “Not Same”. See the following Java program. In the following program, valueOf() is not used.
Predict the output of the following program. This example is contributed by Bishal Dubey.
Explanation: Two objects will be created here. First object which is pointed by X due to calling of new operator and second object will be created because of Auto-boxing.
This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Java.util.BitSet class methods in Java with Examples | Set 2
- Shadowing of static functions in Java
- How does default virtual behavior differ in C++ and Java ?
- How are Java objects stored in memory?
- How are parameters passed in Java?
- Are static local variables allowed in Java?
- final variables in Java
- Default constructor in Java
- Assigning values to static final variables in Java
- Comparison of Exception Handling in C++ and Java
- Does Java support goto?
- Arrays in Java
- Inheritance and constructors in Java
- More restrictive access to a derived class method in Java
- Comparison of static keyword in C++ and Java