How substring() method works in java?


Actual implementation of substring method is :

public String substring(int beginIndex, int endIndex) {
	if (beginIndex < 0) {
	    throw new StringIndexOutOfBoundsException(beginIndex);
	}
	if (endIndex > count) {
	    throw new StringIndexOutOfBoundsException(endIndex);
	}
	if (beginIndex > endIndex) {
	    throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
	}
	return ((beginIndex == 0) && (endIndex == count)) ? this :
	    new String(offset + beginIndex, endIndex - beginIndex, value);
  }
  String(int offset, int count, char value[]) {
	this.value = value;
	this.offset = offset;
	this.count = count;
    }


In this if begin index and end Index are not out of bound then it will create a new string having the original complete string . So here it is maintaining the original value of the string and assigning the original again in the constructor.
So we can say that if it has a big string like 1 GB and we need a little substring and after that if the original one want to be garbage collected then it can not because it used in substring and it can not be free, so we can say it tends to memory leak.