Deniz Cetinalp
Deniz Cetinalp

Reputation: 911

Understanding == and equals

I learned that == checks if the references being compared are the same,, while .equals() compares the two states. So then why can we use == inside the .equals() method?

Like for example:

public boolean equals(Object o){
        //cast o to SimpleBankAccount
        SimpleBankAccount b = (SimpleBankAccount)o;

        //check if all attributes are the same
        if ((this.balance == b.balance) && (this.accountNumber == b.accountNumber)){
            return true;
        }
        else{
            return false;
        }
    }

Why would the this.balance and b.balance have the same reference?

Upvotes: 1

Views: 99

Answers (7)

rgettman
rgettman

Reputation: 178263

If this equals method works, then it's because the balance and accountNumber variables are primitive types such as int or double, and == does compare the values for primitive types.

Upvotes: 0

Jay Parashar
Jay Parashar

Reputation: 56

If you want to compare the value of balance/accountNumber and they are primitives or primitive Wrappers (like Integer) then == is how you compare the value. The wrappers will be autoboxed.

Upvotes: 0

ahjmorton
ahjmorton

Reputation: 965

References are also similar to primitive types along with int, chars and doubles in that when you do == you're literally comparing the binary representation of those types.

Upvotes: 2

christopher
christopher

Reputation: 27346

The equals method is to compare objects. When using the "==" to test for equality, the only time it will function as expected is when it is comparing primitive or native types, or you are actually testing to see if two pointers refer to the same object. That is, balance is more than likely of type int, float or double, which means "==" will test for equality as expected. If balance was of type Balance, then this would not work.

Upvotes: 2

svz
svz

Reputation: 4588

== is normally used inside the equals method to check if the two references are actually the same object. If they are not, further checking goes to see if objects have the same state.

Upvotes: 0

pcalcao
pcalcao

Reputation: 15990

Depends on what balance is.

If balance is a primitive, then == will compare the values, which is correct.

Upvotes: 0

75inchpianist
75inchpianist

Reputation: 4102

because balance is likely a primitive, correct? like an int or a float? so you are comparing the value of balance. With objects you are comparing the references, but with primitives you are comparing the actual data value

Upvotes: 1

Related Questions