Pre-knowledge
For objects, both commands work actually in the same way as String Literals, but the way in which they use memory could be something that is harder to understand.
creating a situation with objects
Adding objects will look like this. The objects could contain the same value (see code –> “ey bro”) but have different memory locations.
*the image shows that object 1 and object 2 are not in the same spot, this means that they have different memory locations.
Scenario’s
1. comparing objects
Object 1 is not equal to object 2 (in this case) because, every object is saved in a new space in memory.
You can use == and .equals():
- As shown in the pages about primitive datatypes and String literals; To compare if the objects have the same memory location you can use the == operator.
- You can also use the .equals() command because the method: equals does nothing more than using an == operator. More info click here.
== |
output is false |
.equals() |
output is false |
2. comparing references
Comparing the memory location of one and the same object will give true
== |
output is true |
.equals() |
output is true |
You can use == and .equals():
- As shown in the pages about primitive datatypes and String literals; To compare if the objects have the same memory location you can use the == operator.
- You can also use the .equals() command because the method: equals does nothing more than using an == operator. More info click here.
3. Comparing object values
But sometimes it’s your goal to compare the value of objects as shown in the code of step 4.
Mostly this is what you imagine in your head:
WRONG, the value in the objects is not a new text but a reference to a text
Actually, this is your situation:
You forgot to specify what you want to compare. You created 2 objects, therefore you have 2 objects in space. However, the text is saved in one place. Therefore, specify the variable you want to compare. And you will get your solution:
== |
output is true |
.equals() |
output is true |