Java Programming - Java.lang Class - Discussion
Discussion Forum : Java.lang Class - Finding the output (Q.No. 2)
2.
What will be the output of the program?
public class WrapTest
{
public static void main(String [] args)
{
int result = 0;
short s = 42;
Long x = new Long("42");
Long y = new Long(42);
Short z = new Short("42");
Short x2 = new Short(s);
Integer y2 = new Integer("42");
Integer z2 = new Integer(42);
if (x == y) /* Line 13 */
result = 1;
if (x.equals(y) ) /* Line 15 */
result = result + 10;
if (x.equals(z) ) /* Line 17 */
result = result + 100;
if (x.equals(x2) ) /* Line 19 */
result = result + 1000;
if (x.equals(z2) ) /* Line 21 */
result = result + 10000;
System.out.println("result = " + result);
}
}
Answer: Option
Explanation:
Line 13 fails because == compares reference values, not object values. Line 15 succeeds because both String and primitive wrapper constructors resolve to the same value (except for the Character wrapper). Lines 17, 19, and 21 fail because the equals() method fails if the object classes being compared are different and not in the same tree hierarchy.
Discussion:
5 comments Page 1 of 1.
Lena said:
9 years ago
Just try some interesting addition: for values between -128 and 127, if used without "new" operator like this:
Long i = 42L;
Long i2 =42L;
The result of (i==i2) will be true because Java caches objects instances from the range -128 to 127.
But in the case with new operator Java will always create different objects so == will return false even in this range.
Long i = 42L;
Long i2 =42L;
The result of (i==i2) will be true because Java caches objects instances from the range -128 to 127.
But in the case with new operator Java will always create different objects so == will return false even in this range.
Bill said:
1 decade ago
It's obvious.
Result = 0.
/*Only line 15 is correct*/
Result = Result+10;
Then result = 10.
Result = 0.
/*Only line 15 is correct*/
Result = Result+10;
Then result = 10.
Kawish said:
1 decade ago
I don't, understand x equal y concept and how the answer will be 10?
Zakir said:
9 years ago
Anybody can explain this question.
Rahul said:
10 years ago
How can it possible?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers