-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?

9
  • They are both equal to some string and null at the same time? Commented Apr 8, 2015 at 22:04
  • Please clarify but all of them are null. Commented Apr 8, 2015 at 22:04
  • 1
    THey are not null. They are empty. There's a big difference. Commented Apr 8, 2015 at 22:05
  • 1
    No @Programmer NULL and empty are two separate concepts in Java. Learn that quickly or you'll be both confused and writing buggy code Commented Apr 8, 2015 at 22:06
  • 1
    Empty string "" , string with spaces " " and null string are 3 different things Commented Apr 8, 2015 at 22:09

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Sotirios Delimanolis - Woops Its my Mistake. Corrected.
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.

Comments

-2

You can see if the characters match

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

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

3 Comments

Think I misunderstood his question...
I guess so, question is not clear, if he wants to compare empty strings or null strings
You can always edit or delete your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.