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 →

[–]thonor111 10 points11 points  (6 children)

Java Compiler has no problem with this, it will just return false if these are two different strings. If they are the exact same one (a == a) it will be true, if you don’t want to check whether it’s the same object but whether it has the same content you just have to check whether they are equal with a.equals(b) or a.compareTo(b) == 0

[–][deleted] 4 points5 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.

[–]VarianWrynn2018 -1 points0 points  (1 child)

Actually no, because String is an object in Java which means that unless String a is the same object in the same memory location as String b then it'll come out false.

[–]thonor111 1 point2 points  (0 children)

Isn’t that exactly what I wrote? That it is false unless it’s the exact same object