java的String类判断null或空的方法

针对String字符串对象的判空和是否为null有三个方向:

  • 直接比较。例如str == null或者str==""。
  • java的String类自带的isEmpty()方法,如果对象为null,则不能使用该方法,会报空指针异常。
  • StringUtils工具类的isEmpty和isBlank方法,与String类自带的isEmpty()区别见表格和代码。
  • 工具类的isBlank方法是最全能的。
  • 工具类的isEmpty不认为" "为空。
  • String类的isEmpty无法对null进行判断,同时也不认为" "为空。

StringUtils.isEmpty

StringUtils.isBlank

str.isEmpty

""

true

true

true

" "

false

true

false

nul

true

true

报错


        System.out.println("".isEmpty());//true
        System.out.println("  ".isEmpty());//false
        System.out.println(" 1111 ".isEmpty());//false
//        System.out.println(null.isEmpty());//java.lang.NullPointerException

        System.out.println("---------");

        System.out.println(StringUtils.isEmpty(""));//true
        System.out.println(StringUtils.isEmpty("  "));//false
        System.out.println(StringUtils.isEmpty(" 1111 "));//false
        System.out.println(StringUtils.isEmpty(null));//true

        System.out.println("---------");

        System.out.println(StringUtils.isNotEmpty(""));//false
        System.out.println(StringUtils.isNotEmpty("  "));//true
        System.out.println(StringUtils.isNotEmpty(" 1111 "));//true
        System.out.println(StringUtils.isNotEmpty(null));//false

        System.out.println("---------");

        System.out.println(StringUtils.isBlank(""));//true
        System.out.println(StringUtils.isBlank("  "));//true
        System.out.println(StringUtils.isBlank(" 1111 "));//false
        System.out.println(StringUtils.isBlank(null));//true
#基础知识##资料##八股文#
全部评论

相关推荐

03-01 21:45
中北大学 Python
孤蓝长空:请你说一下为什么你用websocket而不是http,请你说一下什么是rpc,为什么用rpc,你的rpc的传输协议是JSON,xml还是什么 请你描述一下你的鉴权流程(完整的) 我问的是第二个项目,随便问的哈哈哈
开工第一帖
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务