public class Main {
public static void main(String[] args) {
String s;
s += "Hello world!";
System.out.println(s);
}
}上面的代码为何会输出 "nullHello world!", 而不是"Hello world!", 也就是说为什么String对象在没有初始化的情况下对其进行字符串连接会将null值当作"null"来处理?java 环境为 jdk1.6.0_u18 和 jdk_1.6.0_u21
为什么不是将null值在做字符串连接时当作空字符串""来处理呢, 感觉这样更符合编程习惯一些啊.
不好意思, 因为我这里没有java的环境, 没怎么注意, 应该是这样的public class Main { static String s; public static void main(String[] args) {
s += "Hello world!";
System.out.println(s);
}}
static变量,自动初始化为null.
s += "Hello world!";
这句话被编译器处理为
StringBuilder builder = new StringBuilder();
builder.append(s);
builder.append("Hello world!");然后去看StringBuilder的append(String str)方法: public StringBuilder append(String str) {
super.append(str);
return this;
}再看其父类的append 方法: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;
}
static StringBuffer sb = new StringBuffer();
public static void main(String[] args) {
sb.append(s);
sb.append("Hello world!");
System.out.println(sb);
System.out.println(s);
}