java中java.lang.String.concat(String str)使用注意

我在使用concat時,並不清楚concat的實現原理。我就使用concat方法將兩個字符串拼接起來webImageRootPath.concat(path)。可是後來代碼報了java.lang.NullPointerException異常,檢查webImageRootPath並不異常爲空,當時很納悶怎麼會報空指針異常呢。從網上搜索以後發現,原來是path這個值爲null。java

  1. public String concat(String str) {
  2. int otherLen = str.length();
  3. if (otherLen == 0) {
  4. return this;
  5. }
  6. char buf[] = new char[count + otherLen];
  7. getChars( 0, count, buf, 0);
  8. str.getChars( 0, otherLen, buf, count);
  9. return new String(0, count + otherLen, buf);
  10. }

上面是concat的源碼實現。原來使用concat方法時,參數str也不能爲null,不然就會包空指針異常。web

相關文章
相關標籤/搜索