public class ArrToStr {
static String str ;
static String str1 = "";
static String str2 = "";
public static void main(String[] args){
System.out.println(str==str1);
System.out.println(str instanceof Object);
System.out.println(str1 instanceof Object);
System.out.println(str);
System.out.println("null".equals(str));
System.out.println(str==null);
System.out.println(str1.length());
System.out.println(str1==str2);
String str3 = "abc";
String str4 = str3;
String str5 = new String("abc");
String str6 = new String("abc");
System.out.println(str3==str4);
System.out.println(str5==str6);
System.out.println(str + str3);
}
}
通过上述测试代码分析:- 比较null和""的不同
- String str = null是指str这个变量指向空对象;而“”是一个包含空字符的字符串对象。
- str == str1返回false,因为“”和null不在同一内存地址空间,也就是说,着两个变量没有指向同一对象。
- "null".equals(str)返回false。因为空串的值不是“null”。
- 空串str1是可以调用String对象的方法的,比如str1.length()的值为0;而str.length()将会抛出异常NullPointerException。
- 比较==和equals的不同
- str3==str4返回true,因为着两个变量指向同一个对象"abc"(即内存中同一地址空间);而str==str6返回false,因为用new在开辟了两个不同的空间来存储两个“abc”对象,这样着两个变量所指向的地址就不同。
- equals指的是当字符串不为空,并且字符串的值一样时就返回true。
- 为什么str打印出来是“null”?
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
- 为什么str+str3打印出来是“nullabc”?
public StringBuilder append(String str) {
super.append(str);
return this;
}
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
java运行过程中特殊的疑问一定不要轻易放过,查看源码会找到答案。