16

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
  • 11,433
  • 6
  • 73
  • 64
Alireza aslami
  • 690
  • 6
  • 18
  • 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

24

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
  • 145
  • 1
  • 2
  • 18
Blackbelt
  • 152,872
  • 27
  • 286
  • 297
6

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() }