首页javastringJava Data Type - 如何检查字符串是否为空

Java Data Type - 如何检查字符串是否为空

我们想知道如何检查字符串是否为空。

To test whether a String object is empty. The length of an empty string is zero.

There are three ways to check for an empty string:

  • isEmpty() method.
  • equals() method.
  • Get the length of the String and check if it is zero.

The following code shows how to use the three methods:

public class Main { public static void main(String[] args) { String str1 = "Hello"; String str2 = ""; // Using the isEmpty() method boolean empty1 = str1.isEmpty(); // Assigns false to empty1 boolean empty2 = str2.isEmpty(); // Assigns true to empty1 // Using the equals() method boolean empty3 = "".equals(str1); // Assigns false to empty3 boolean empty4 = "".equals(str2); // Assigns true to empty4 // Comparing length of the string with 0 boolean empty5 = str1.length() == 0; // Assigns false to empty5 boolean empty6 = str2.length() == 0; // Assigns true to empty6 } }