日期:2014-05-20  浏览次数:20680 次

一个关于null的简单问题
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;
首先b在栈内存中定义了一个句柄。
但是b并没有指向任何具体的对象。

string相加的时候,他就是null,具体的我也解释不清楚。一直就是这样。
------解决方案--------------------
举例:
有一张表:employees,字段:id,name,telno,address
<td> 电话号码: </td>
<td> <%=employee.getTelno%> </td>
显示:
电话号码:null

------解决方案--------------------
在字符串像加的时候 不是字符串的会自动转化成字符串再相加

针对LZ的问题也就是说

a.toString()+b.toString()+c.toString()

答案就是 anullc

不知道这样解释对不对`
------解决方案--------------------
to happy_sky()
b.toString()是错误的,b为null是不能有toString()方法的。
String b=null;
System.out.println(b);
输出结果为null
此时b应该被认为是基本数据类型,可能类似类中字段未赋值。
望高手出来指点
------解决方案--------------------
因为String d=a+b+c;被编译器编译成 new StringBuffer().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;
}
------解决方案--------------------
因为String d=a+b+c;被编译器编译成 String b = new StringBuffer().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;
}

------解决方案--------------------
写错了,是
因为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;
}
------解决方案--------------------
受blh(股市奋斗几十年,一夜回到解放前: ()启发
看看了print方法对String输出的处理。
public void print(String s) {
if (s == null) {
s = "null ";
}
write(s);
}
jdk中的源代码才是无敌的。
受教了。
谢谢blh
------解决方案--------------------
StringBuilder这个class不是1.5才有的吗?