33

I want to check the value of a String in my in Android project. I saw two functions to check my String value:

item.isBlank()

and

item.isEmpty()

What is difference between them?

Paulo Merson
  • 13,270
  • 8
  • 79
  • 72
Aslami.dev
  • 880
  • 8
  • 19
  • Does this answer your question? [StringUtils.isBlank() vs String.isEmpty()](https://stackoverflow.com/questions/23419087/stringutils-isblank-vs-string-isempty) – xszym Sep 07 '20 at 13:50
  • @xszym That's a Java question for a different class (same content, of course). – Maarten Bodewes Sep 07 '20 at 13:56

2 Answers2

52

item.isEmpty() checks only the length of the the string

item.isBlank() checks the length and that all the chars are whitespaces

That means that

  • " ".isEmpty() should returns false
  • " ".isBlank() should returns true

From the doc of isBlank

Returns true if this string is empty or consists solely of whitespace characters.

nt4f04und
  • 182
  • 1
  • 2
  • 21
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
8

In future, you can read documentation and see the code from IDE just click Ctrl+B or Command+B. This is written in documantation for isEmpty method:

/**
 * Returns `true` if this char sequence is empty (contains no characters).
 *
 * @sample samples.text.Strings.stringIsEmpty
 */
@kotlin.internal.InlineOnly
public inline fun CharSequence.isEmpty(): Boolean = length == 0

And for isBlank:

 * Returns `true` if this string is empty or consists solely of whitespace characters.
 *
 * @sample samples.text.Strings.stringIsBlank
 */
public actual fun CharSequence.isBlank(): Boolean = length == 0 || indices.all { this[it].isWhitespace() }