1. 程式人生 > >java中String為null及其加減法的輸出結果

java中String為null及其加減法的輸出結果

  String s = null;
  System.out.println(s);
  s += "abc";
  System.out.println(s);
  s += null;
  System.out.println(s);

輸出結果:null

                  nullabc

                  nullabcnull

除錯了一遍,發現java封裝了導致的結果,要是c++準報錯! 

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 void print(String s) {
		if (s == null) {
		    s = "null";
		}
        write(s);
}