今天项目查bug时,发现一个空指针问题,查了半天,最终定位到是有String +运算造成的.于是就写了一个测试:
public static void main(String [] arg0){
String a = null;
String b = "null";
String c = "===";
String ac = a+c;
String bc = b+c;
System.out.println("a+c: " + ac);
System.out.println("b+c: " + bc);
System.out.println("a+c == b+c " + ac.equals(bc));
}
运行结果:
a+c: null===
b+c: null===
a+c == b+c true
原因: Java只是不支持自定义运算符重载,这个String类的+就是运算符重载,也是Java中仅有的一个运算符重载,它是通过编译器实现的,在语法解析阶段就已经确定了.
如:a+c是通过 new StringBuilder().append(a).append(c)实现的.
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
/**
* Appends the specified string to this character sequence.
* <p>
* The characters of the {@code String} argument are appended, in
* order, increasing the length of this sequence by the length of the
* argument. If {@code str} is {@code null}, then the four
* characters {@code "null"} are appended.
* <p>
* Let <i>n</i> be the length of this character sequence just prior to
* execution of the {@code append} method. Then the character at
* index <i>k</i> in the new character sequence is equal to the character
* at index <i>k</i> in the old character sequence, if <i>k</i> is less
* than <i>n</i>; otherwise, it is equal to the character at index
* <i>k-n</i> in the argument {@code str}.
*
* @param str a string.
* @return a reference to this object.
*/
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
通过注释 If {@code str} is {@code null}, then the four characters {@code "null"} are appended
我们可以发现当String字符为空(null)时,append()方法会添加 字符串”null”.