Java Programming - Java.lang Class - Discussion

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);
    }
}

[A]. result = 1
[B]. result = 10
[C]. result = 11
[D]. result = 11010

Answer: Option B

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.


Kawish said: (Apr 26, 2015)  
I don't, understand x equal y concept and how the answer will be 10?

Bill said: (May 11, 2015)  
It's obvious.

Result = 0.

/*Only line 15 is correct*/

Result = Result+10;

Then result = 10.

Rahul said: (Nov 21, 2015)  
How can it possible?

Zakir said: (Mar 7, 2016)  
Anybody can explain this question.

Lena said: (May 12, 2016)  
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.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.