Вопрос

In the JDK documentation it states that the String method isEmpty() is true for any string of length 0.

This is obviously true for the empty string "".

Are there any other string for which this is the case? I have tested line breaks and carriage returns and they have a length. I have not yet tested characters with appended backspaces.


Edit: I appreciate all the additional information in all the good answers below, however I have accepted what I believe is the most direct answer to the question.

Это было полезно?

Решение

A "string of length zero" means that the string contains no characters at all, and that includes invisible, zero-width, etc. Unicode characters.

Therefore a string whose on-screen representation is completely blank and zero-width is still non-empty if it contains a character.

Другие советы

A String of length 0 contains 0 characters. So no, there are no other Strings that would be empty except for the empty String.

See the implementation of it:

670     public boolean isEmpty() {
671         return count == 0;
672     }

Where count is the number of characters in the String.

That will be the case only if there are no characters in the String, which is only "".

From Java 1.6 onwords String.isEmpty() is available to use. It is faster than String.equals("") call. Strings store a count variable initialized in the constructor, since Strings are immutable.

isEmpty() compares the count variable to 0, while equals will check the type, string length, and then iterate over the string for comparison if the sizes match.

from javadoc-

public boolean isEmpty()
Returns true if, and only if, length() is 0.
Returns:
true if length() is 0, otherwise false
Since:
1.6

There are two usefull methods in apaches commons org.apache.commons.lang3.StringUtils class

isBlank(CharSequence cs)

Checks if a CharSequence is whitespace, empty ("") or null.

isEmpty(CharSequence cs)

Checks if a CharSequence is empty ("") or null.

Maybe this is, what you're looking for, if you didn't want to reinvent the wheel.

From the JavaDoc

String#isEmpty() Returns true if, and only if, length() is 0.

So, there are no other cases where isEmpty() will return true

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top