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
#基础知识##资料##八股文#
全部评论

相关推荐

牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
那一天的Java_J...:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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