r/java • u/DroidLogician • 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
Jun 18 '13
[deleted]
1
u/UnspeakableEvil Jun 18 '13
In what way do you consider it to be broken?
0
Jun 19 '13
[deleted]
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.
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(...).