Java string null как проверить

Содержание
  1. How to check if String is not null and empty in Java? Example
  2. 3 Ways to check if String is null or empty in Java
  3. 1st solution — using isEmpty() method
  4. 2nd solution — Using length() function
  5. 3rd solution — Using trim() method
  6. Rukovodstvo
  7. статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.
  8. Java: проверьте, является ли строка пустой, пустой или пустой
  9. Введение В Java существует четкое различие между пустыми, пустыми и пустыми строками. * Пустая строка — это объект String с присвоенным значением, но его длина равна нулю. * Пустая строка вообще не имеет значения. * Пустая строка содержит только пробелы, не является ни пустой, ни нулевой, поскольку ей присвоено значение и ее длина не равна 0. Строка nullString = null; Строка emptyString = ""; Строка blankString = ""; В этом уроке мы рассмотрим, как проверить,
  10. Вступление
  11. Использование длины строки
  12. Использование метода isEmpty ()
  13. Использование метода equals ()
  14. Использование класса StringUtils
  15. Заключение
  16. Java Program to Check if a String is Empty or Null
  17. Example 1: Check if String is Empty or Null
  18. Example 2: Check if String with spaces is Empty or Null

How to check if String is not null and empty in Java? Example

In Java, since null and empty are two different concepts, it’s a little bit tricky for beginners to check if a String is both not null and not empty. A String reference variable points to null if it has not been initialized and an empty String is a String without any character or a string of zero length. Remember, a String with just whitespace may not be considered as empty String by one program but considered as empty String by others, so, depending upon your situation, you can include the logic to check for that as well. A String with just white space is also referred to as a blank String in java. In this tutorial, I will teach you a couple of right ways to test if a String is not null and not empty in Java.

Читайте также:  Python bytecode to code

Btw, I am expecting that you are familiar with basic Java Programing and Java API in general. If you are a complete beginner then I suggest you first go through a comprehensive course like The Complete Java Masterclass on Udemy to learn more about core Java basics as well as such gems from Java API.

3 Ways to check if String is null or empty in Java

Here are my three solutions to this common problem. Each solution has its pros and cons and a special use case like the first solution can only be used from JDK 7 onward, the second is the fastest way to check if String is empty and the third solution should be used if your String contains whitespaces.

1st solution — using isEmpty() method

This is the most readable way to check for both whether String is null or not and whether String is empty or not. You can see from the below code that the first check is a null check and the second check is for emptiness.

A couple of things to remember about this solution is that you must keep the order the same because isEmpty() is a non-static method and if called on the null reference it will throw NullPointerException.

Since we are first doing a null check and then an empty check using the && operator, which is a short circuit AND operator. This operator will not check for emptiness if String is null hence no NPE. This is also a good trick to avoid NPE in Java.

Btw, you must be careful with the order you carry the null and emptiness check. For example, if you reverse the order of checks i.e. first call the isEmtpy() method and then do the null check, you will get the NullPointerException. In fact, it is one of the most common causes of NullPointerExcetpion in Java.

Читайте также:  Html set icon in title

The second thing to keep in mind is that the isEmpty() method is available from Java SE 6 onwards, so this code will not work in Java 5 or the lower version. There you can use the length() method to check emptiness, as shown in the second example.

How to check if String is not null and not empty in Java

2nd solution — Using length() function

This is the universal solution and works in all versions of Java, from JDK 1.0 to Java 8. I highly recommend this method because of the portability advantage it provides. It is also the fastest way to check if String is empty in Java or not.

One thing which is very important here is that if String contains just white space then this solution will not consider it as an empty String. The emptiness check will fail because the string.length() will return a non-zero value. If you are considering the String with only whitespaces as empty then use the trim() method as shown in the third example.

3rd solution — Using trim() method

This is the third way to check whether the String is empty or not. This solution first calls the trim() method on the String object to remove the leading and trailing white spaces.

You can use this solution if your program doesn’t consider a String with only white-space as a non-empty. If you load data from the database or stored data into the database it’s better to trim() them before using them to avoid pesky issues due to whitespaces.

That’s all about how to check if String is not null and not empty in Java. You can use any of the above three methods but you must remember the pros and cons of each method. Sometimes you need to use the trim() method if your program’s requirement doesn’t consider a String with the only whitespace as non-empty, but other times, you might want to use the length() function to consider String with just whitespaces as empty String in Java.

As suggested by others, if you are using Google Guava, Spring, or Apache commons then just check their StringUtils class, you might get a method that does this for you like StringUtils.isBlank() from Apache Commons. Remember, even Joshua Bloch has advised in Effective Java to learn and use library functions, whenever possible, but only if you understand the fundamentals behind it.

  • When to use the intern() method of String in Java? (answer)
  • Why is String Immutable and final in Java? (answer)
  • Why is a character array better than a String for storing the password in Java? (reason)
  • How substring() method works in Java 6? (answer)
  • The difference between String literal and new() String object in Java? (answer)
  • How to prepare for Java interviews? (guide and resources)

Источник

Rukovodstvo

статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.

Java: проверьте, является ли строка пустой, пустой или пустой

Введение В Java существует четкое различие между пустыми, пустыми и пустыми строками. * Пустая строка — это объект String с присвоенным значением, но его длина равна нулю. * Пустая строка вообще не имеет значения. * Пустая строка содержит только пробелы, не является ни пустой, ни нулевой, поскольку ей присвоено значение и ее длина не равна 0. Строка nullString = null; Строка emptyString = ""; Строка blankString = ""; В этом уроке мы рассмотрим, как проверить,

Вступление

В Java существует четкая разница между null , пустыми и пустыми строками.

  • Пустая строка — это String с присвоенным значением, но его длина равна нулю.
  • null строка вообще не имеет значения.
  • Пустая строка содержит только пробелы , не является ни пустой, ни null , поскольку ей присвоено значение и ее длина 0
 String nullString = null; String emptyString = ""; String blankString = " "; 

В этом руководстве мы рассмотрим, как проверить, является ли String пустым, пустым или пустым в Java :

Использование длины строки

Как упоминалось ранее, строка пуста, если ее длина равна нулю. Мы будем использовать метод length() , который возвращает общее количество символов в нашей строке.

 String blankString = " "; if(blankString == null || blankString.length() == 0) System.out.println("This string is null or empty"); else System.out.println("This string is neither null nor empty"); 

Приведенный выше код даст следующий результат:

 This string is null or empty 

Строка является пустой, так что , очевидно , ни null , ни пустой. Теперь, основываясь только на длину, мы можем на самом деле не различать между строками , которые содержат только пробельную или любой другой символ, поскольку пробел является Character .

Примечание. Важно сначала null проверку, поскольку оператор короткого замыкания ИЛИ || немедленно сломается при первом true условии. Если строка фактически имеет значение null , все остальные условия перед ней NullPointerException .

Использование метода isEmpty ()

Метод isEmpty() возвращает true или false зависимости от того, содержит ли наша строка какой-либо текст. Его легко объединить в цепочку с помощью string == null и даже можно различать пустые и пустые строки:

 String string = "Hello there"; if (string == null || string.isEmpty() || string.trim().isEmpty()) System.out.println("String is null, empty or blank."); else System.out.println("String is neither null, empty nor blank"); 

Метод trim() удаляет все пробелы слева и справа от String и возвращает новую последовательность. Если строка пуста , после удаления всех пробелов она будет пустой, поэтому isEmpty() вернет true .

Запуск этого фрагмента кода даст нам следующий результат:

 String is neither null, empty nor blank 

Использование метода equals ()

Метод equals() сравнивает две заданные строки на основе их содержимого и возвращает true если они равны, или false если нет:

 String string = "Hello there"; if(string == null || string.equals("") || string.trim().equals("")) System.out.println("String is null, empty or blank"); else System.out.println("String is neither null, empty nor blank"); 

Примерно так же, как и раньше, если обрезанная строка — «» , она либо была пустой с самого начала, либо была пустой строкой с 0..n :

 String is neither null, empty nor blank 

Использование класса StringUtils

Apache Commons — популярная библиотека Java, обеспечивающая дополнительные функции. StringUtils — один из классов, которые предлагает Apache Commons. Этот класс содержит методы, используемые для работы со Strings , аналогичные java.lang.String .

Если вы не знакомы с вспомогательными классами Apache Commons, мы настоятельно рекомендуем прочитать нашеРуководство по классу StringUtils .

Поскольку для этого подхода мы будем использовать Apache Commons, давайте добавим его как зависимость:

  org.apache.commons commons-lang3 3.11  

Или, если вы используете Gradle:

 compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.11' 

Одно из ключевых различий между StingUtils и String заключается в том, что все методы из класса StringUtils являются нулевыми . Он дополнительно предоставляет несколько методов, которые мы можем использовать для этого, включая StringUtils.isEmpty() и StringUtils.isBlank() :

 String nullString = null; if(nullString == null) < System.out.println("String is null"); >else if(StringUtils.isEmpty(nullString)) < System.out.println("String is empty"); >else if(StringUtils.isBlank(nullString))

В дополнение к ним также существуют их обратные StringUtils.isNotEmpty() и StringUtils.isNotBlank() , однако вы можете достичь той же функциональности, используя ! ):

 if(StringUtils.isNotEmpty("")) System.out.println("String is not empty"); // Equivalent to if(!StringUtils.isEmpty("")) System.out.println("String is not empty"); 

Заключение

Строка — это объект, представляющий последовательность символов. Java предоставляет множество различных методов для обработки строк. В этой статье мы использовали некоторые из этих методов, такие как isEmpty() , equals() , StringUtils.isEmpty() и length() чтобы проверить, является ли String null , пустым или пустым.

Licensed under CC BY-NC-SA 4.0

Источник

Java Program to Check if a String is Empty or Null

To understand this example, you should have the knowledge of the following Java programming topics:

Example 1: Check if String is Empty or 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

In the above program, we have created

  • a null string str1
  • an empty string str2
  • a string with white spaces str3
  • method isNullEmpty() to check if a string is null or empty

Here, str3 only consists of empty spaces. However, the program doesn’t consider it an empty string.

This is because white spaces are treated as characters in Java and the string with white spaces is a regular string.

Now, if we want the program to consider strings with white spaces as empty strings, we can use the trim() method. The method removes all the white spaces present in a string.

Example 2: Check if String with spaces is Empty or 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"; >> >

In the above example, notice the condition to check empty string

Here, we have used the trim() method before isEmpty() . This will

Hence, we get str is EMPTY as output.

Источник

Оцените статью