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?
isBlank() vs isEmpty() Both methods are used to check for blank or empty strings in java. The difference between both methods is that isEmpty() method returns true if, and only if, string length is 0. isBlank() method only checks for non-whitespace characters. It does not check the string length.
Practically speaking, you should generally use String. isBlank if you expect potentially whitespace strings (e.g. from user input that may be all whitespace), and String. isEmpty when checking fields from the database, which will never contain a string of just whitespace.
StringUtils isEmpty() Example in Java. The isEmpty() method doesn't check for whitespace. It will return false if our string is whitespace. We need to use StringUtils isBlank() method to check whitespace.
To check if string is empty in Kotlin, call isEmpty() method on this string. The method returns a boolean value of true, if the string is empty, or false if the string is not empty.
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 trueFrom the doc of isBlank
Returns true if this string is empty or consists solely of whitespace characters.
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With