Java.lang Class

Q1: What will be the output of the program?
public class Test178 
{ 
    public static void main(String[] args) 
    {
        String s = 'foo'; 
        Object o = (Object)s; 
        if (s.equals(o)) 
        { 
            System.out.print('AAA'); 
        } 
        else 
        {
            System.out.print('BBB'); 
        } 
        if (o.equals(s)) 
        {
            System.out.print('CCC'); 
        } 
        else 
        {
            System.out.print('DDD'); 
        } 
    } 
}

A AAACCC

B AAADDD

C BBBCCC

D BBBDDD

ANS:A - AAACCC

The output is the same even when comparing with another string that only its value is the same (but in such a case operaton == returns false), since o object points now to the equals method of the instance of String that doesn't care about addresses difference :

String s1 = new String("foo");
String s2 = new String("foo");
Object o = (Object)s1;
if (s2.equals(o))
{
System.out.print("AAA");
}
else
{
System.out.print("BBB");
}
if (o.equals(s2))
{
System.out.print("CCC");
}
else
{
System.out.print("DDD");
}



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.