+ 2

Why do I have this output?

Please, check my code named "why true" and explain me please, why do we use "==" with 2 Strings and get true?

2nd Apr 2017, 5:35 PM
Gleb Yeremeyev
Gleb Yeremeyev - avatar
3 Respostas
+ 18
Because strings cannot be compared using ==. You have to use .equals() method. http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
2nd Apr 2017, 5:38 PM
Hatsy Rei
Hatsy Rei - avatar
+ 12
== checks if two objects have the same adress at the heap. And if you don't use new operator, there will be only one object, if the String value is the same. Java refers to your first object instead of creating another one if the strings are equal. Don't expect this behaviour from other classes... Play it safe, use equals.
2nd Apr 2017, 8:33 PM
Tashi N
Tashi N - avatar
+ 1
@Hatsy Rei I know this clear, but I didn't understand that "==" actually checks if objects both are the same by type (I though that with objects it checks if they have the same memory address). thank you for the link
2nd Apr 2017, 6:33 PM
Gleb Yeremeyev
Gleb Yeremeyev - avatar