-1

How to check a string in java that is empty or not?

For example : string str = " " and string str2 = " " and str3 = ""

str includes 3 spaces, str2 includes 1 space, and str3 has no characters but all of them are empty.

How do I check this in Android?

Programmer
  • 23
  • 1
  • 6

3 Answers3

3

Just check with str.isEmpty() as isEmpty() method will return true for actual length if 0.

As NULL refers to memory assignment of your String str. To check empty String use isEmpty() method.

Update:

In your case, best scenario should be,

if(str != null && str.trim().length() > 0)
{
     // String str is not NULL or not Empty
}else
{
    // String str is NULL or Empty
}
user370305
  • 108,599
  • 23
  • 164
  • 151
0

Null != empty. Null means the variable is not initialized, like: String s; Your str,str2 and str3 are initialized, zo they are not null.

To check for same characters: str.equals("foo"), ("foo" is in your case spaces :) )

NOT str == "foo". The last means you're checking same references.

Dopdop
  • 37
  • 3
-2

You can see if the characters match

if (str.equals ("")) {
  // true
}

if (str3.equals ("   ")) {
  // true
}
jb15613
  • 359
  • 4
  • 12