Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.5k points)
Aren't they the same thing?

1 Answer

0 votes
by (11.3k points)
edited by

No, they aren't the same thing.

'==' compares the value of two variables. Say, if i=3 and j=3, then if you use 'j==i' to receive a boolean value with regards to the equality of the two integer values, you'll receive a 'true' in return. If you compare two object names with '==', the contents of the objects will not be compared but rather the address/reference stored by the variables will. These are the addresses that point to the object itself. 

On the other hand, if you compare two objects with '.equals', you get a return value based on the comparison of the value contained inside the objects, what the object's pointed address itself is pointing towards. You cannot use .equals for variables that don't represent objects. (Strings, for instance)

If you're confused as to where to use what and you're looking to learn java, consider using '==' for numeric comparisons and  '.equals' for alpha-numeric comparisons. 

Browse Categories

...