I think I found a contradiction. In JavaSyntaxZero Level 3 Lecture 6, this is said about strings:
However, in the previous lecture, it shows two strings with the exact same text, having different references that point to memory:
Could somebody explain why the strings with identical text have different references?
I don't understand this about Strings and equality.
Resolved
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
7 November 2023, 20:40solution
The double == operator checks primitives for equal values, however with Objects it compares the memory address of the operands instead. Strings are objects and that is what the diagrams you included are highlighting.
Strings are objects with a bit of a curve ball in that the String pool was implemented to save memory by pointing duplicate Strings to the same memory address. This can be over ridden by just specifying that you want any same String to have a unique memory address by using the "new" keyword and creating like any other Object. If we implemented a String the normal way and then creating a new String(), for a unique memory address, with the same text to compare using the equality operator the result would be false as the two Strings have different memory addresses:
Also the methods of the String class return "new" Strings (the methods that return Strings, obviously the .length() method does not). This is why you would get false if you compared the results of the same method being called twice on one String as in the example of .toUpperCase() from your question. Another example showing the same thing with a different method call:
This is the important part to remember ↓
If you want to compare String values, or compare any Object, always use the .equals() method. Otherwise you are comparing memory addresses and this can have unexpected results if you use the String classes methods.
+3
Jesú
7 November 2023, 20:59
Superb, thank you my friend. I also found that String has a method called intern() which can convert a string object to a string literal.
+2
Guadalupe Gagnon
7 November 2023, 21:30
Nice, I never knew that about .intern(), so i learned something new today too.
0