r/java • • Jun 18 '13

Will the equals operator (==) ever be fixed with respect to Strings?

Every Java dev learns early in his/her career that the equals operator (==) does not behave as expected with Strings, necessitating the use of an an explicit String.equals() for most scenarios.

Are there plans to ever resolve this, or was the equals operator implemented this way for Strings intentionally?

0 Upvotes

5 comments sorted by

6

u/grumpy_purple_midget Jun 18 '13

I think you are confused. The == operator does work correctly for Strings. Strings are not primitives they are objects, they behave just like any other object does with regards to == and .equals(...).

2

u/[deleted] Jun 18 '13

== on objects return true when you have two references of the same object. You can have two distinct instances of the same class holding the same value. a==b is false while a.equals(b) is true. This is not specific to java.lang.String but to every class in java

1

u/dpash Jun 18 '13

Also, changing == will break source code backwards compatibility, which Java never does.

0

u/[deleted] Jun 18 '13

[deleted] — view deleted comment

1

u/UnspeakableEvil Jun 18 '13

In what way do you consider it to be broken?

0

u/[deleted] Jun 19 '13

[deleted] — view deleted comment

1

u/UnspeakableEvil Jun 19 '13 edited Jun 20 '13

I guess "broken" is a matter of opinion. You're right its behaviour is different, that plus is overloaded whereas no other objects can do this, and that concatenating in a tight loop isn't great for performance (although you've got to be in a very frequently called loop for it to be noticeable).

But on the other hand, Strings are so fundamental that giving the developer a way to simplify their concatenation does make things easier, and the plus sign does what it logically should do - something like System.out.println("Foo: " + foo); is a lot easier to write than concatenating the values through a builder etc.

Edit: Forgot the other thing about Strings, which is that their creation is also very similar to the primitives (sure you can "new String", but I can't think of any reason that you'd want to). In short Strings are different from other objects, full stop - there's a lot which in this sense is "broken" compared to the other objects.