Guess the output of the following Java Program.
// file name: Main.java public class Main { public static void main(String args[]) { Integer x = 400, y = 400; if (x == y) System.out.println("Same"); else System.out.println("Not Same"); } }
Output:
Not Same
Since x and y refer to different objects, we get the output as “Not Same”
The output of the following program is a surprise from Java.
// file name: Main.java public class Main { public static void main(String args[]) { Integer x = 40, y = 40; if (x == y) System.out.println("Same"); else System.out.println("Not Same"); } }
Output:
Same
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.
// file name: Main.java public class Main { public static void main(String args[]) { Integer x = new Integer(40), y = new Integer(40); if (x == y) System.out.println("Same"); else System.out.println("Not Same"); } }
Output:
Not Same
Predict the output of the following program.
class GFG { public static void main(String[] args) { Integer X = new Integer(10); Integer Y = 10; // Due to auto-boxing, a new Wrapper object // is created which is pointed by Y System.out.println(X == Y); } }
Output:
false
Explanation:
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.