String a="a";
String b=null;
String c="c";
String d=a+b+c;
System.out.println(d);//得到:anullc为什么把b的null当是字符串了?我觉得,应该这样才得到anullc的啊。
String a="a";
String b="null";
String c="c";
String d=a+b+c;
System.out.println(d);//得到:anullc
String b=null;
String c="c";
String d=a+b+c;
System.out.println(d);//得到:anullc为什么把b的null当是字符串了?我觉得,应该这样才得到anullc的啊。
String a="a";
String b="null";
String c="c";
String d=a+b+c;
System.out.println(d);//得到:anullc
首先b在栈内存中定义了一个句柄。
但是b并没有指向任何具体的对象。string相加的时候,他就是null,具体的我也解释不清楚。一直就是这样。
b.toString()是错误的,b为null是不能有toString()方法的。
String b=null;
System.out.println(b);
输出结果为null
此时b应该被认为是基本数据类型,可能类似类中字段未赋值。
望高手出来指点
嘿嘿,我也知道一直都是这样的。也不知道怎么解释好。
to happy_sky()
b.toString()是错误的,会抛出NullPointerException()。哎,原来是20分的帖子,没人来啊,我已经加到100分了。希望吸引更加多的人来解释一下。
public AbstractStringBuilder append(String str) {
if (str == null) str = "null"; //******
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}
public AbstractStringBuilder append(String str) {
if (str == null) str = "null"; //******
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}
因为String d=a+b+c;被编译器编译成 String b = new StringBuilder().append(a).append(b).append(c).toString();StringBuffer.append(Object obj)对null进行特殊处理,代码如下
public AbstractStringBuilder append(String str) {
if (str == null) str = "null"; //******
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}
那以前那些版本,是怎么加的?
看看了print方法对String输出的处理。
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
jdk中的源代码才是无敌的。
受教了。
谢谢blh
以前是StringBuffer
效果应该是一样的。
就是我开始写的,用StringBuffer :)