Java will set constant constants (trailing strings) and literals (create one instance of each row in the internal pool), and this way you can get the same instance even if it is "created" by concatenation.
As others have already pointed out, compiler optimization will actually turn concatenation into a single literal ("ab").
You can never fully rely on the semantics of ==
String, so equals(..)
should always be used.
Edit: To clarify the above sentence:
With objects, ==
always means that links are compared, and it will always return true if both links are the same. However, you cannot always rely on getting the same object reference (for example, in your example, when a simple final
changes the behavior or in frameworks such as Hibernate, etc.) - that’s why you should usually use equals(...)
.
Of course, you can use ==
if you need physical equality (the same object) instead of logical equality (the same value).
Another example where ==
will have different results, although both in terms of location should both be true:
Integer l1 = 0; Integer l2 = 0; l1 == l2; //most often true, since Integer objects up to 127 are cached Integer l1 = 1000; Integer l2 = 1000; l1 == l2; //most often false, since those are not cached anymore
Please note that with “more often” I mean that this can change between versions of Java (if not different JVMs), although this is not very likely.
source share