For some reason, the people that make java decided that ==
shouldn't be used to compare Strings, so you have to use
checkNine.equals("99999");
Look at the following code:
String str1 = "abc";
String str2 = str1;
In the first line, a new string is created and stored in your computer's memory. str1
itself is not that string, but a reference to that string. In the second line, str2
is set to equal str1
. str2
is, like str1
, only a reference to a place in memory. However, rather than creating an entirely new string, str2
is a reference to the same place in memory that str1
is a reference to. ==
checks if the references are the same, but .equals()
checks if the each character in a string is the same as the corresponding character in the other string.
boolean bool1 = (str1 == str2);
boolean bool2 = str1.equals(str2);
If this code were added to the code above that, both bool1
and bool2
would be true.
String str1 = "abc";
String str2 = new String(str1);
boolean bool1 = (str1 == str2);
boolean bool2 = str1.equals(str2);
In this case bool2
is still true, but bool1
is false. This is because str2
isn't set to equal str1
, so it isn't a reference to the same place in memory that str1
is a reference to. Instead, new String(str1)
creates an entirely new string that has the value of str1
. str1
and str2
are references to two different places in memory. They contain the same value, but are fundamentally different in that they are stored in two different places, and therefore are two different things.
If I replaced new String(str1)
with "abc"
or str1
, bool1
would be true, because without the key word new
, the JVM only creates a new string to store in memory if absolutely necessary. new
forces the JVM to create an entirely new string, whether or not any place in memory already has the same value as the new string being created.
.equals()
is slow but generally more useful than ==
, which is far faster but often does not always give the desired result. There are many times when ==
can be used with the same result as .equals()
, but it can be difficult to tell when those times are. Unless you a knowledgeable programmer making something where speed is important, I would suggest that you always use .equals()
.