Java Programming - Java.lang Class - Discussion

Discussion Forum : Java.lang Class - Finding the output (Q.No. 6)
6.
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"); 
        } 
    } 
}
AAACCC
AAADDD
BBBCCC
BBBDDD
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
16 comments Page 2 of 2.

Belete said:   10 years ago
Very interesting and motivation questions for Java programming.

Janani Santhanakumar raju said:   9 years ago
Its is obvious that both s and o's reference are same. In If conditions, it is given s.equals(o) which means to check whether both are referring to the same object. Since this condition is true it prints "AAA" and same way with the o.equals(s) so it prints "CCC".

Alexander said:   9 years ago
At o.equals(s) Object class equals method is executed & inside this equals method if both references i.e o[default "this" inside non static equals() method] & s refer to same object then 'true' is returned. thus;

sop("CCC") is executed.

At s.equals(o) , String class equals() method is executed, inside this equals method 1st code checks whether both references refer to same object see(https://dzone.com/articles/how-string-equals-method-works), hence true is returned & sop("AAA") is executed.

Seema said:   8 years ago
Yes, I too got the same output, i.e AAACCC.

Adam Prog said:   8 years ago
I have 2 comments:

1.A super class that is casted to a sub class is not fully "equals" because the static members remain of the super class. So if the static members of the subclass are needed, its not enough to check equals (or == operator).

2.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");
}

Lahul said:   8 years ago
Correct answer is B.

Because object class equals method compares address whereas in String class its overridden to compare the content.

So o.equals (s) will be false.


Post your comments here:

Your comments will be displayed after verification.