String类的substring方法

下列程序的输出是什么?

class A { public static void main(String[] a) {
    String v = “base”;      v.concat(“ball”);
    v.substring(1,5);       System.out.println(v);  }
}

分析:由于String是不可变的,当执行v.concat("ball")时,v本身还是指向“base”,当再执行v.substring(1,5)时,会报出界异常

 

如下为concat的源码:可以看到,最后返回的是新的字符串

public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }

如下是substring源码:

public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}

public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
}

 

posted @ 2016-10-12 11:46  博学善思。。ljd  阅读(4483)  评论(0编辑  收藏  举报