Difference between isEmpty() and isBlank() Method in java 11

痴心易碎 提交于 2019-12-30 11:15:16

问题


Java 11 has added A new instance method isBlank() to java.lang.String class.

What's the basic difference between the existing isEmpty and newly added isBlank() method?


回答1:


isEmpty()

The java string isEmpty() method checks if this string is empty. It returns true, if the length of the string is 0 otherwise false e.g.

System.out.println("".isEmpty()); // Prints - True
System.out.println(" ".isEmpty()); //Prints - False 

Java 11 - isBlank()

The new instance method java.lang.String.isBlank() returns true if the string is empty or contains only white space, where whitespace is defined as any codepoint that returns true when passed to Character#isWhitespace(int).

boolean blank = string.isBlank();

Before Java 11

boolean blank = string.trim().isEmpty();

After Java 11

boolean blank = string.isBlank();



回答2:


Java 11 added has new method called .isBlank() in String class

  1. isBlank() method is equal to str.trim().isEmpty() in earlier to java 11 versions
  2. isEmpty() : Returns true if, and only if, length() is 0

This is the internal implementation of isBlank() method in String class of java 11

public boolean isBlank() {
    return indexOfNonWhitespace() == length();
}

private int indexOfNonWhitespace() {
    if (isLatin1()) {
        return StringLatin1.indexOfNonWhitespace(value);
    } else {
        return StringUTF16.indexOfNonWhitespace(value);
    }
}


来源:https://stackoverflow.com/questions/51299126/difference-between-isempty-and-isblank-method-in-java-11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!