comparison with strings having white space
Solution 1
You should check if the name
is null before you do that, otherwise it looks good. (except for, it should be if
instead of If
):
//either
if(name != null) {
if(name.equalsIgnoreCase("This is Android") {
}
}
//or
if("This is Android ".equalsIgnoreCase(name)) {
Update:
When you are comparing strings, the whitespaces count. So, basically "Hello world" and "Hello world " are not equal.
You need to use the .trim()
method to ignore the surrounding whitespaces.
name = name.trim(); //since strings are immutable you need to assign return value to name
if("This is Android".equalsIgnoreCase(name)) {
Solution 2
"This is Android " is different from "This is Android" and equalsIgnoreCase
will return false. You can use trim()
to remove spaces and the start or the end of the String
s.
Hope this helps!
Solution 3
Always keep constant String on left hand side in equals, this ensures no NPE:
like this :
if ("This is Android ".equalsIgnoreCase(str1)) {
// start activity 1
} else {
// start activity 2
}
In case you dont want space then add trim()
:
if ("This is Android ".trim().equalsIgnoreCase(str1)) {
// start activity 1
} else {
// start activity 2
}
Solution 4
if("This is Android".equalsIgnoreCase(name))
// start activity 1
} else {
// start activity 2
}
or the bullet-proof (in case user pasted value with unwanted spaces at the end of string)
if(name != null && "This is Android".equalsIgnoreCase(name.trim()))
// start activity 1
} else {
// start activity 2
}
kzs
Updated on October 30, 2020Comments
-
kzs over 3 years
Sorry if it's a silly question. I need to compare with a name which has three words separated by one white space. If the name is null or "This is Android" i would do something, otherwise i do something else. For example, is the following code right to do this comparison?
if((name==null)||(name.equalsIgnoreCase("This is Android"))) { //start activity 1 } else { //start activity 2 }
-
Miquel over 12 yearsWhy do you go toString on a String literal? Also, why invert the order?
-
Bhesh Gurung over 12 years@Miquel: Thanks for spotting. Did not pay attention while copy from OP. If you invert if the null check is not required so.
-
Chris Aldrich over 12 years@gurung - unless there is a need, you do not need to check for null. That is covered by the equalsIgnoreCase call.
-
kzs over 12 yearsactually "This is Android" in the code. is what i meant...edited my question again..sorry for the typo.
-
Bhesh Gurung over 12 years@ChrisAldrich: That does not make any sense. Suppose:
name
is null then how isequalsIgnoreCase
going to covername.equalsIgnoreCase
??? It's that simple. -
Dimitris Makris over 12 yearsThen the answer is yes. The comparison is ok.
-
viktor over 12 yearsI would never use
string != null string.equals("literal")
and its variants. It's bad practice and it should not be even mentioned.