r/learnjava • u/Willy988 • Aug 27 '21
Why to never use == with Strings and instead use .equals()
In class we were discussing this and basically I understood == tests the EXACT same thing... since Strings are each their own object, we need a special method to check for if they are actually the same words. Furthermore, == tests the address I believe?
Here's the confusing part for me... Java has optimized == so SOMETIMES "hello" == "hello" will return true even if they are two unique Strings... but "hell" += "o" == "hello" returns false. Why ?
4
u/loehnertz Aug 28 '21
I made a video about the topic on my channel "The Self-Taught Software Engineer", where I explain this in detail and show it to you on an example: https://youtu.be/DM15CT1X_zI
If you have any questions, leave a comment under the video ideally :)
2
3
u/thisisjustascreename Aug 27 '21
"hell" += "o" doesn't compile, since you can't assign to a string literal, but assuming you meant "hell" + "o" == "hello", that is always false because the + operator returns a new dynamically created string object at runtime, which (barring a non-standard compiler optimization) cannot ever be the same object as the "hello" object in your code which the compiler creates.
2
u/Willy988 Aug 27 '21
Thank you, makes sense- but why will "hello" == "hello" be true if they are different objects?
Also, is everything else I typed making sense? Just curious if I understood correctly...
7
u/funnythrone Aug 27 '21
That's a Java compiler optimisation. If there are multiple instances of a String literal with the same string, Java uses the same object underneath. So they aren't different objects if you are using the same literal. However if you are concatenating 2 strings, even if the output is same, Java doesn't do the optimisation. It might happen in a future release, but it is not something we should consider.
Java has a lot of intricacies in the underlying implementation. It is important as a Java developer to not depend on the internal implementation unless we have no other choice.
-2
u/AutoModerator Aug 27 '21
You seem to try to compare
Stringvalues with==or!=.This approach does not work in Java, since
Stringis an object data type and these can only be compared using.equals().See Help on how to compare
Stringvalues in our wiki.Your post is still visible. There is no action you need to take.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
3
u/chickenmeister Aug 27 '21
assuming you meant "hell" + "o" == "hello", that is always false
Your comment is mostly right, but this isn't quite true.
"hell" + "o"is a constant expression, which allows the result to be interned, and therefore be the same object as"hello".System.out.println("hell"+"o" == "hello"); // prints 'true'You can even get the same behavior when concatenating with numeric literals or constants:
System.out.println("abc123" == "abc"+123); // prints 'true' final double pi = 3.14; System.out.println("pi is 3.14" == "pi is "+pi); // prints 'true'1
u/AutoModerator Aug 27 '21
You seem to try to compare
Stringvalues with==or!=.This approach does not work in Java, since
Stringis an object data type and these can only be compared using.equals().See Help on how to compare
Stringvalues in our wiki.Your post is still visible. There is no action you need to take.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
-3
u/AutoModerator Aug 27 '21
You seem to try to compare
Stringvalues with==or!=.This approach does not work in Java, since
Stringis an object data type and these can only be compared using.equals().See Help on how to compare
Stringvalues in our wiki.Your post is still visible. There is no action you need to take.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
7
8
u/Ph03nix89 Aug 27 '21
You need to do some reading up on the String Constant Pool and the difference between Stack and Heap memory(Strings and their construction are usually discussed in detail here for reasons that will become clear).
Sorry for the short answer but it's a very dense topic that is usually covered across multiple chapters in books. This will get you what you need though.
4
u/jacob_scooter Aug 28 '21
keep in mind for most objects (not strings of course), equals() is the same as ==. string has its own version of it however that compares the contents of the string rather than the objects themselves
0
u/loehnertz Aug 31 '21
That is absolutely incorrect...for ANY object in Java!
Duration.ofMinutes(10) == Duration.ofMinutes(10)will evaluate tofalsewhileDuration.ofMinutes(10).equals(Duration.ofMinutes(10))will evaluate totrue. Please don't make these kind of claims, this can be easily fact-checked!0
u/jacob_scooter Aug 31 '21
wow, I’ve never seen someone so confident despite being so wrong. first, I said MOST objects. not ALL objects, because some override Object’s version of equals, like the one you mentioned.
and you’re right, it can be fact checked. here’s the source code for .equals() in Object:
149 public boolean equals(Object obj) {
150 return (this == obj);
151 }
wow, that’s crazy, it’s the same thing! now if you’ve been coding in java for a while (which is highly doubtful), you’d know that most objects don’t override the .equals() method. not ALL objects, MOST objects. finish your MOOC courses before you start giving or criticizing answers
0
u/loehnertz Aug 31 '21
What do you mean? Can you name any types apart from
Objectitself andEnum<T>where this holds (that==givestrue)? I cannot think of any other one (not counting primitives ofc since they are not objects to begin with) in the entire JDK.2
u/jacob_scooter Aug 31 '21 edited Aug 31 '21
are you serious? Scanner, Random, every Input and Output stream, THREAD. these are just the ones I can think of off the top of my head. not to mention that libraries, frameworks, and APIs other than the JVM exist, with many of them not implementing .equals(). and all those classes you create? believe it or not, they’re objects too! you really need to stop talking for your own good.
1
u/loehnertz Aug 31 '21
I'm sorry! I must've misinterpreted your point then:
equals() is the same as ==
I figured that you meant that one can just substitute with
==to check for equality in terms of the contents of an object (like the characters in aString).This was a misunderstanding then, now I got your point and you are right ofc! Sorry again!
2
u/mikezyisra Aug 27 '21
It looks like you’ve got your answer. But the “why does does “hello” == “hello” return true?” is a bit more complicated and it relates to how memory is laid out in the JVM and what the compiler (?) does I believe. Similar cases of “hell” + “o” == “hello” or similar might depend on compiler optimization level or jvm, so you really shouldn’t rely on it. More or less, the string “hello” which you never modify doesn’t need to be stored on the heap, so two identical ‘immutable’ “hello”s can be references to some one unique address somewhere.
2
u/feral_claire Aug 27 '21
Similar cases of “hell” + “o” == “hello” or similar might depend on compiler optimization level or jvm, so you really shouldn’t rely on it
That is guaranteed to be true by the specification so it can be relied on. However practically you are almost never doing things like this so it's not super useful and it is prone to errors (because you made a mistake or the code changed and didn't update the comparison) so it's best to always use .equals() unless there is a very good reason not to.
1
u/mikezyisra Aug 28 '21
Thanks for the additional info, I didn't know that. But yeah we make the same point, thumbs up
2
Aug 28 '21 edited Aug 28 '21
Note that testing using == and String interning are two related, but different concepts altogether. Since others have covered both of these in some detail, let me give you an example of why using == is a bad idea, and why you should always use equals when comparing strings (and objects in general).
Consider the following RMI example (basically Java's native way of doing RPC):
The Machinery:
import java.rmi.Naming;
public class Server {
public static void main(String[] args) {
try {
ICompare stub = new CompareImpl();
Naming.rebind("rmi://localhost:9999/compare", stub);
} catch (Exception ex) {
System.err.println(ex);
}
}
}
import java.rmi.Naming;
public class Client {
public static void main(String[] args) {
try {
ICompare stub = (ICompare)Naming.lookup("rmi://localhost:9999/compare");
stub.compareUsingEqualsOperator("hello");
stub.compareUsingEqualsMethod("hello");
} catch (Exception ex) {
System.err.println(ex);
}
}
}
The actual logic:
import java.rmi.RemoteException;
import java.rmi.Remote;
public interface ICompare extends Remote {
public void compareUsingEqualsOperator(String hello) throws RemoteException;
public void compareUsingEqualsMethod(String hello) throws RemoteException;
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class CompareImpl extends UnicastRemoteObject implements ICompare {
public CompareImpl() throws RemoteException {
super();
}
@Override
public void compareUsingEqualsOperator(String hello) throws RemoteException {
if (hello == "hello") {
System.out.println("[compareUsingEqualsOperator] Matched");
} else {
System.out.println("[compareUsingEqualsOperator] Not matched");
}
}
@Override
public void compareUsingEqualsMethod(String hello) throws RemoteException {
if (hello.equals("hello")) {
System.out.println("[compareUsingEqualsMethod] Matched");
} else {
System.out.println("[compareUsingEqualsMethod] Not matched");
}
}
}
Running it:
$ javac *.java
$ rmiregistry 9999
$ java Server // this is the server JVM instance
$ java Client // this is the client JVM instance
Output on the server side:
[compareUsingEqualsOperator] Not matched
[compareUsingEqualsMethod] Matched
[compareUsingEqualsOperator] Not matched
[compareUsingEqualsMethod] Matched
...So, basically we send a string (literal) between JVM instances, and try to compare them using == and equals. The former will always fail since references are specific to a particular JVM instance (there are ways of sharing references across JVMs, but that's beyond the scope of this discussion) whereas the latter will always pass (since we're comparing the actual value contained in the string input). Note that this is completely independent of how and when string interning is done on the client and server JVMs.
tl;dr: Always use equals.
1
u/AutoModerator Aug 28 '21
You seem to try to compare
Stringvalues with==or!=.This approach does not work in Java, since
Stringis an object data type and these can only be compared using.equals().See Help on how to compare
Stringvalues in our wiki.Your post is still visible. There is no action you need to take.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
Aug 31 '21
`==` compares if the two are the same object, while `.equals` usually compares values. This is a very dumbed down explanation, but usually if you're working with objects you want to use `.equals` because normally you're comparing their values and not if the compared objects are actually the same.
If you're comparing primitives like `int` then it doesn't matter, because literally the only thing you're comparing is the value.
0
u/AutoModerator Aug 27 '21
You seem to try to compare String values with == or !=.
This approach does not work in Java, since String is an object data type and these can only be compared using .equals().
See Help on how to compare String values in our wiki.
Your post is still visible. There is no action you need to take.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
6
1
u/-HoldMyBeer-- Sep 17 '21
I remember working on resolving a bug for about 2 hours in an API I was working on. I couldn't get a particular document from a nosql db. I checked the code about 100 times but still couldn't find any issue. Then, just to be sure, I checked the meaning of == in strings and well, I felt really stupid lol. I used equals() and finally got the correct output. I found out that == works only if the two string objects point to the same memory location. It's really important to know this peculiar concept in java as one could easily come across with such a bug.
0
Aug 27 '21
[deleted]
20
u/Willy988 Aug 27 '21
Holy cow, this is so awesome. Thank you for this reply, that makes so much sense and is so cool!
-8
u/AutoModerator Aug 27 '21
You seem to try to compare
Stringvalues with==or!=.This approach does not work in Java, since
Stringis an object data type and these can only be compared using.equals().See Help on how to compare
Stringvalues in our wiki.Your post is still visible. There is no action you need to take.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
-9
u/Jadeyfoxx Aug 27 '21
Wrong. s1 might work with s2 sometimes because the JVM does string pooling. Google 'string pooling java' and the intern method of the string class.
6
u/feral_claire Aug 27 '21
s1 might work with s2 sometimes because the JVM does string pooling
Not sometimes, always. Identical string constants are guaranteed to be the same object by the specification, 100% of the time.
Wrong
They are correct, I think you misunderstood what they wrote.
0
Aug 27 '21
[deleted]
-9
u/Jadeyfoxx Aug 27 '21
Yes but it doesn't work 100% of the time.
9
u/chickenmeister Aug 27 '21 edited Aug 27 '21
s1 == s2will be true 100% of the time in this example. See JLS §3.10.5 String Literals:Moreover, a string literal always refers to the same instance of class
String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.29) - are "interned" so as to share unique instances, as if by execution of the method String.intern (§12.5).And also 12.5:
Loading of a class or interface that contains a string literal (§3.10.5) or a text block (§3.10.6) may create a new
Stringobject to denote the string represented by the string literal or text block. (This object creation will not occur if an instance ofStringdenoting the same sequence of Unicode code points as the string represented by the string literal or text block has previously been interned.)Having said that, I wouldn't recommend relying on this behavior. You should always use s1.equals(s2).
4
u/Jadeyfoxx Aug 27 '21
https://docs.oracle.com/javase/specs/jvms/se10/html/jvms-4.html#jvms-4.4 more info here.
Edit: and here https://openjdk.java.net/jeps/334
3
u/cal-cheese Aug 28 '21
This is actually a compiler optimisation, not a VM optimisation,
s1ands2is actually optimised to referred to the same object in the classfile constant pool.
5
u/cal-cheese Aug 27 '21
==operator checks the equality of the object identity, i.e. 2 objects==each other if they are indistinguishable from each other. Currently, in Java, each object has its own unique identity, but not a unique address. As a result, understanding that==tests for address equality is not correct.Java does not optimised
==so that"hello" == "hello", the thing got optimised here is how Java stores theStringobject, which leads to 2 string literal declarations with the same contents are detected and assigned to a singleStringobject.