Java Programming - Java.lang Class - Discussion

3. 

What will be the output of the program?

public class BoolTest 
{
    public static void main(String [] args) 
    {
        int result = 0;

        Boolean b1 = new Boolean("TRUE");
        Boolean b2 = new Boolean("true");
        Boolean b3 = new Boolean("tRuE");
        Boolean b4 = new Boolean("false");

        if (b1 == b2)  /* Line 10 */
            result = 1;
        if (b1.equals(b2) ) /* Line 12 */
            result = result + 10;
        if (b2 == b4)  /* Line 14 */
            result = result + 100;
        if (b2.equals(b4) ) /* Line 16 */
            result = result + 1000;
        if (b2.equals(b3) ) /* Line 18 */
            result = result + 10000;

        System.out.println("result = " + result);
    }
}

[A]. 0
[B]. 1
[C]. 10
[D]. 10010

Answer: Option D

Explanation:

Line 10 fails because b1 and b2 are two different objects. Lines 12 and 18 succeed because the Boolean String constructors are case insensitive. Lines 14 and 16 fail because true is not equal to false.


Ramu said: (Dec 9, 2010)  
is this(case insensitive) only for Boolean

Karthik said: (Oct 2, 2011)  
How came this output?

Saroja said: (Sep 17, 2012)  
Yes the Boolean String constructors are insensitive. But how the value of result would be 10010. Would you please explain briefly?

Pradeep said: (Nov 26, 2012)  
As b1 and b2 are two different objects hence condition (b1 == b2) will fail where as condition on line 12 (b1.equals(b2)) will succeed.

Only line 12 & 18 will succeed.

Line 12 : result = 0 + 10 = 10.
Line 18: result = 10 + 10000 = 10010.

Krishna said: (Jan 4, 2013)  
Yes the Boolean string constructor are insensitive so result 10010.

Yash said: (Feb 22, 2014)  
Can not understand properly will anyone please explain?

Swati Jadhav said: (Dec 14, 2016)  
I didn't get the correct answer. Can anyone show me memory representation of string in this example?

Michael said: (Aug 6, 2017)  
What is the difference between b1 == b2 and b1 equals (b2)?

Naveen said: (Oct 12, 2019)  
b1==b2 - compare only the memory address of the string present.
b1.equals(b2) - compare the string which presents in the particular memory address.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.