Проверка строки на пустоту и null в Java — isEmpty и isBlank

В этой программе мы научимся проверять, является ли строка пустой (empty) или равной null.

Пример 1: проверка строки на null или пустоту

class Main {
  public static void main(String[] args) {

    // create null, empty, and regular strings
    String str1 = null;
    String str2 = "";
    String str3 = "  ";

    // check if str1 is null or empty
    System.out.println("str1 is " + isNullEmpty(str1));

    // check if str2 is null or empty
    System.out.println("str2 is " + isNullEmpty(str2));

    // check if str3 is null or empty
    System.out.println("str3 is " + isNullEmpty(str3));
  }

  // method check if string is null or empty
  public static String isNullEmpty(String str) {

    // check if string is null
    if (str == null) {
      return "NULL";
    }

    // check if string is empty
    else if(str.isEmpty()){
      return "EMPTY";
    }

    else {
      return "neither NULL nor EMPTY";
    }
  }
}

Вывод:

str1 is NULL
str2 is EMPTY
str3 is neither NULL nor EMPTY

В программе выше мы создали:

  • null-строку str1;

  • пустую строку str2;

  • строку с пробелами str3;

  • метод isNullEmpty(), который проверяет, является ли строка null или пустой.

Здесь str3 состоит только из пробелов. Однако программа не считает её пустой строкой.

Это потому, что пробельные символы в Java считаются полноценными символами, а строка с пробелами — обычной строкой.

Совет

Если мы хотим, чтобы программа считала строки с пробелами пустыми, можно использовать метод trim(). Он удаляет все пробельные символы из строки.


Пример 2: проверка строки с пробелами на пустоту или null

class Main {
  public static void main(String[] args) {

    // create a string with white spaces
    String str = "    ";

    // check if str1 is null or empty
    System.out.println("str is " + isNullEmpty(str));
  }

  // method check if string is null or empty
  public static String isNullEmpty(String str) {

    // check if string is null
    if (str == null) {
      return "NULL";
    }

    // check if string is empty
    else if (str.trim().isEmpty()){
      return "EMPTY";
    }

    else {
      return "neither NULL nor EMPTY";
    }
  }
}

Вывод:

str is EMPTY

В примере выше обратите внимание на условие проверки пустой строки:

else if (str.trim().isEmpty())

Здесь перед isEmpty() мы вызвали trim(). Это:

  1. удаляет все пробельные символы внутри строки;

  2. проверяет, является ли строка пустой.

В результате получаем вывод str is EMPTY.