bhawesh kumar bhawesh kumar - 1 month ago 19
Java Question

Access object by reference

What will be the output of following program? I am not aware of object assignment or references.

class ObjEx
{
public static void main(String arg[])
{
ObjEx ob=new ObjEx();
Object o = ob;

if(o==ob)
System.out.println("1");
if(o!=ob)
System.out.println("10");
if(o.equals(ob))
System.out.println("101");
if(ob.equals(o))
System.out.println("1101");

}
}


Options: A)1 (B)10 (C)101 (D)1101
Please explain me that what will be output and how is it possible?
I am getting output on my screen as but I am not getting this program:

1

101

1101

Answer

Here if(o==ob) you are comparing references and for the last 2 cases:

if(o.equals(ob))
if(ob.equals(o))

In java equals is an operation to compare the objects and this operation is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

Comments