Java中String字符串:空字符串、存放空的字符串、null的区别
Java String字符串中有三种特殊的字符串:空字符串、存放空的字符串、字符串为Null,如下所示:
String str1 = "";
String str2 = " ";
String str3 = null;
字符串str1表示空字符串,字符串str2表示存放空的字符串,字符串str3表示为null的字符串。
那么他们的长度是多少以及他们调用isEmpty()函数的情况,本文针对这一问题,做了对比试验。
@Test
public void test06() {
String str1 = "";
String str2 = " ";
String str3 = null;
int str1Length = str1.length();
int str2Length = str2.length();
// int str3Length = str3.length(); // 报错
System.out.println("the length of str1:"+str1.length()); // 0
System.out.println("the length of str2:"+str2.length()); // 1
// System.out.println("the length of str3:"+str3.length()); // 报错
if (str1.isEmpty()){
System.out.println("-------str1为空-----");
}
if (str2.isEmpty()){ // str2不为空
System.out.println("-------str2为空-----");
}
// if (str3.isEmpty()){ // 报错
// System.out.println(str3);
// }
System.out.println("-------调用isBlank()方法------");
if(StringUtils.isBlank(str1)){
System.out.println("------调用isBlank()方法---str1为空-----");
}
if(StringUtils.isBlank(str2)){
System.out.println("------调用isBlank()方法---str2为空-----");
}
if(StringUtils.isBlank(str3)){
System.out.println("------调用isBlank()方法---str3为空-----");
}
}
测试结果:
the length of str1:0
the length of str2:1
-------str1为空-----
-------调用isBlank()方法------
------调用isBlank()方法---str1为空-----
------调用isBlank()方法---str2为空-----
------调用isBlank()方法---str3为空-----
结果分析:
1、str1="“和str2=” " 在编译的过程中会给其分配相应的空间,str3 = null则不会被分配空间,所以导致其调用isEmpty()会报空指针异常。
2、str1=""不存放任何字符,导致其调用length()输出为0,调用isEmpty输出为空(true)
3、str2存放空格字符,所以调用length()显示长度为1,调用isEmpty()输出False。值得注意的是,当str2中存放多个空格时,每个空格都会占用一个长度