在Java中,判断一个字符串是否为空或者为 null 是一个常见的操作。以下是几种常见的方法来实现这个判断:
1. 使用 == 和 isEmpty()
这是最基础的方式,用来判断字符串是否为 null 或者为空字符串。
1 2 3 4 5 | String str = ...; if (str == null || str.isEmpty()) { // 字符串为 null 或空字符串 } |
2. 使用 == 和 length()
另一种方式是检查字符串的长度是否为0。
1 2 3 4 5 | String str = ...; if (str == null || str.length() == 0 ) { // 字符串为 null 或空字符串 } |
3. 使用 Apache Commons Lang
如果你使用了Apache Commons Lang库,可以使用 StringUtils 类,它提供了更加简洁的方法。
首先,需要在你的项目中添加依赖(如果使用Maven):
1 | org.apache.commonscommons-lang33.12.0 |
然后,可以使用如下方法:
1 2 3 4 5 6 7 | import org.apache.commons.lang3.StringUtils; String str = ...; if (StringUtils.isEmpty(str)) { // 字符串为 null 或空字符串 } |
4. 使用 Java 11 的 isBlank()
Java 11 引入了 String 类的新方法 isBlank(),它不仅检查字符串是否为空,还会检查字符串是否只包含空白字符(如空格、制表符等)。
1 2 3 4 5 | String str = ...; if (str == null || str.isBlank()) { // 字符串为 null、空字符串或仅包含空白字符 } |
5. 使用 Objects 类的 requireNonNullElse 方法
在需要提供默认值的情况下,可以使用 Objects 类的 requireNonNullElse 方法,它可以在字符串为 null 时提供一个默认值。
1 2 3 4 5 6 7 8 9 | import java.util.Objects; String str = ...; str = Objects.requireNonNullElse(str, "" ); if (str.isEmpty()) { // 字符串为 null 或空字符串 } |
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | import org.apache.commons.lang3.StringUtils; public class StringTest { public static void main(String[] args) { String str1 = null ; String str2 = "" ; String str3 = " " ; // 方法1: 使用 == 和 isEmpty() if (str1 == null || str1.isEmpty()) { System.out.println( "str1 is null or empty" ); } if (str2 == null || str2.isEmpty()) { System.out.println( "str2 is null or empty" ); } // 方法2: 使用 == 和 length() if (str2 == null || str2.length() == 0 ) { System.out.println( "str2 is null or empty" ); } // 方法3: 使用 Apache Commons Lang if (StringUtils.isEmpty(str2)) { System.out.println( "str2 is null or empty (using StringUtils)" ); } // 方法4: 使用 Java 11 的 isBlank() if (str3 == null || str3.isBlank()) { System.out.println( "str3 is null, empty or blank" ); } // 方法5: 使用 Objects 的 requireNonNullElse str1 = Objects.requireNonNullElse(str1, "" ); if (str1.isEmpty()) { System.out.println( "str1 is null or empty (using Objects.requireNonNullElse)" ); } } } |
到此这篇关于java中判断String类型为空和null的几种方法的文章就介绍到这了,更多相关java String类型为空和null内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!