3

In Java, what is the difference between "" (empty quotes) and " " (quotes with a single space) and how do I test the former in terms of a char?

4 Answers 4

6

"" represents the empty string. " " is not empty, it contains a single space character.

You can't test the former in terms of a char, as there are no characters: test for it in terms of a String: it is the String of length zero, and String.equals("") returns true for the empty string.

Or in terms of char arrays, the empty string corresponds to the char array of length zero, e.g.:

char noChars[] = new char[0];
String str = new String(noChars);
// now str is the empty String
1
  • I tried testing for the null character '\0' but it seems that is also not equivalent to an empty string. I also found this answer which explained why.
    – jgatcher
    Aug 22, 2012 at 11:00
4

"" - Is an Empty String, and it has a lenght of zero, try calling length() method on it.

" " - A String with 1 space.

3
“” - Empty Sting - String with 0 length
“ ” - single space - String with 1 length
1

Both "" and " " are String objects which are 0 and 1 in length respectively. Here is their content representation in terms of char primitives:

"" - empty char[] array
" " - char[] { ' ' } :- Char aray with single char entry

Best to use String.equals when comparing the contents of strings. Here just a length() check is necessary though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.