Reputation: 1111
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
}
Upvotes: 3
Views: 37038
Reputation: 1297
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
}
Upvotes: 1
Reputation: 51030
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)) {
Upvotes: 4
Reputation: 5183
"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!
Upvotes: 7
Reputation: 20323
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
}
Upvotes: 2