Junior — Middle
What happens if you create a string using new String and compare it with the literal " " using the == operator?
sobes.tech AI
Answer from AI
When creating a string using new String(" "), a new object is created on the heap that contains a string with a single space. The literal " " refers to a string from the string pool.
The operator == compares references to objects, not their contents. Therefore, the expression:
new String(" ") == " "
will return false, because these are different objects in memory.
To compare the contents of strings, you should use the .equals() method, for example:
new String(" ").equals(" ") // will return true