先浪一句,代码在下
为了知其然,实例要放前。为了所以然,解释放中间。为了ps:,备注最后面。
判断字符串是否为空
实例代码
//以下三种状态都能过滤 String abc = null;//第一种空 //String abc = ""; //第二种空 //String abc = "aabbcc"; //有值 if (abc == null || abc.isEmpty()) { System.out.println("字符串为空"); }else { System.out.println("字符串有值"); }
解释
字符串第一种空的状态:null
null 表示不存在的东西,没有分配空间给它(所以不能存取值)String aaa = null; if(aaa == null){ System.out.println("字符串为null"); }
字符串第二种空的状态:"" [ 等价于new String() ]
“” 表示定义了一个【长度为空的】字符串,有分配空间给它,但里面没有值String bbb = ""; //下面三种方式都可以判断 "" 这种空 if(bbb.isEmpty()){ System.out.println("empty: "+bbb); } if(bbb.equals("")){ System.out.println("equals: "+bbb); } if(bbb.length()<=0){ System.out.println("length: "+bbb); }
如果bbb=null 上面三种判断方式都会报空指针异常,因为null的含义是没有地址,没有分配任何空间,所以它去调用类的方法都会报异常。
所以判断一个字符串是否为空需要按顺序去判断:
1.首先就要判断是不是null(地址空)
2.然后再判断值空 (地址非空,值空) [长度判断(length()<=0) / 方法判断(isEmpty) / 对比判断(equals("")) ]
(postscript 附言 / 备注 简写Ps:)Ps:
不能这么写String ccc = null; //判断顺序反了 if(ccc.isEmpty() || ccc == null){ System.out.println("不会打这句话,控制台打出空指针异常"); } //不能用 && 符号 if(ccc == null && ccc.isEmpty()){ System.out.println("不会打这句话,控制台打出空指针异常"); }