zoukankan      html  css  js  c++  java
  • JAVA中isEmpty、null、""的区别

    isEmpty()
            分配了内存空间,值为空,是绝对的空,是一种有值(值 = 空)  
     ""
            分配了内存空间,值为空字符串,是相对的空,是一种有值(值 = 空字串)  
     null
            是未分配内存空间,无值,是一种无值(值不存在)

    得出的结论:

    isEmpty()

      1.如果不分配内存空间,不能用isEmpty(),否则报空指针异常

      2.isEmpty()不能分辨出值是空还是空字符串

    null

      1.null只能分辨出值是否不分配内存空间

    “”

      1.不管值是否分配内存空间都不会报错

    例:

    public class Test {
        public static void main(String[] args) {
            //分配内存空间,值为空
            String a = new String();
            //分配内存空间,值为空字符串
            String b = "";
            //未分配内存空间
            String c = null;
    
            if (a != null) {
                System.out.println("a值存在");
            }
            if (b != null) {
                System.out.println("b值存在");
            }
            if (c == null) {
                System.out.println("c值不存在");
            }
            if (a == "") {
                System.out.println("a值存在,为空字符串");
            }
            if (b == "") {
                System.out.println("b值存在,为空字符串");
            }
            //dead code
            if (c == "") {
                System.out.println("c值存在,为空字符串");
            }
            if (a.isEmpty()) {
                System.out.println("a值存在,为空字符串或者为空");
            }
            if (b.isEmpty()) {
                System.out.println("b值存在,为空字符串或者为空");
            }
            // Null pointer access: The variable c can only be null at this location
    //        if (c.isEmpty()) {
    //            System.out.println("String c=null");
    //        }
        }
    
    }

    结果:

    1 a值存在
    2 b值存在
    3 c值不存在
    4 b值存在,为空字符串
    5 a值存在,为空字符串或者为空
    6 b值存在,为空字符串或者为空
  • 相关阅读:
    python中的break 和continue的区别
    查询前几条数据
    python logging日志模块
    python unittest单元测试
    python的数据驱动
    SQL求出优秀、及格人数
    SQL查询去掉重复数据
    vue组件路由守卫钩子函数(beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave)
    前端开发,走浏览器缓存真的很烦,拒绝浏览器走缓存从meta标签做起!
    (转)前端开发-发布一个NPM包之最简单易懂流程
  • 原文地址:https://www.cnblogs.com/aaronRhythm/p/11121065.html
Copyright © 2011-2022 走看看