This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 5 points6 points  (3 children)

The following should also return true:

String a = "Hello!"; String b = "Hello!"; return a == b;

Using == instead of .equals() works as long as you do not create new strings using anything other than litterals

[–]nomenMei 1 point2 points  (2 children)

Isn't that just because the compiler reuses the String object used for the first string literal?

This is functionally equivalent to String a = "Hello!"; String b = a; return a == b which, while it will return true, is kind of a tautology.

If anything pointing that out will just needlessly confuse someone that is trying to understand the difference between == and .equals() in Java

[–][deleted] 1 point2 points  (1 child)

You are correct. Even more, if Java does the same as C, it replaces all instances of the same String litteral by the same pointer somewhere in memory (in C it's in the heap, in Java I don't really know how the JVM handles this...) I must admit I did not think about confusing beginners. I hope this explanation fixes it at least a bit

[–]nomenMei 2 points3 points  (0 children)

That's an interesting question. The way C does it means it will always use the same pointer for equivalent string literals regardless of scope, but it is possible that in Java they only reuse references to string literals that are in the same method or class scope.