Kanwal Gill Kanwal Gill - 1 year ago 83
Java Question

undertsnding object as a parameter

How does same field represents two different values here?below

arn't these two fields same?

class Alpha{
int a,b;

Alpha(int x,int y){
boolean equalTo(Alpha aph){
if(aph.a==a && aph.b==b)return true; //this is the question
else return false;
void guess(Alpha o){
if(o.a==a)System.out.println("correct"); //this is the question
else System.out.println("wrong");
enter image description herepublic class exp {
public static void main(String[] args) {

enter code here
Alpha ob1=new Alpha(12,60); //alpha.a,alpha.b
Alpha ob2=new Alpha(12,60); //alpha.a,alpha.b
Alpha ob3=new Alpha(5,0);

System.out.println("ob1==ob2 : "+ob1.equalTo(ob2));


ob1==ob2 : true


Answer Source

The "==" operator when used with primitives compares the value. However, when dealing with objects, the "==" operator compares the memory address.

Foo a = new Foo();
Foo b = new Foo(); 
System.out.println(a == b); // this will be false since they are different instances

Foo c = new Foo();
Foo d = c;
System.out.println(c == d); // this will be true since they are the same instance

The method equals(Object obj) (which is defined on the Object obj and by default uses the same logic as "==") should be overridden by any object that wants to implement some value type comparison. But even if you override the equals method, it doesn't change the behavior of "==". Whenever you compare to objects for equality, ALWAYS use the equals method unless you really do want to check not the content of the objects but if they are the same instance.

FYI : your equals method is kind of broken (e.g. won't work the way you expect). If for instance you put an Alpha instance in a data structure and then asked if the same object was in it, it would reply as false. This is because you didn't override the Object equals method. What you really want to do is this:

public boolean equals(Object obj) {
    if (obj instanceof Alpha) {
        // Safe to cast since this will only execute if obj is an alpha
        Alpha other = (Alpha) obj;
        // the values are primitives so you can use the "==" operator on them
        return this.a == other.a && this.b == other.b;
    return false;

Also ... if you override equals, always, always, ALWAYS override hashCode or you can't use any hash data structures (think HashMap, HashSet, etc).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download