Tuesday, October 30, 2012

How subString works in Java

In this post, we'll see how substring is implemented in Java and what's the implication of substring method.

It is used to get the parts of the String and define in the String Class and is overloaded like this
public String substring(int beginIndex)
"unhappy".substring(2) returns "happy"

public String substring(int beginIndex,int endIndex) 
"hamburger".substring(4, 8) returns "urge"

Every time you call substring it returns new String because string is immutable.
If beginIndex = endIndex  then it will not throw any exception, it will return empty String.
Same case if beginIndex = length of the String.
It will throw exception only when beginIndex is –ve, larger then endIndex and larger than String length.
Now we will see how substring works:
If you see the implementation of substring() in String class it look like
               if (beginIndex < 0) {
public String substring(int beginIndex, int endIndex) {
                   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);
So basically, it calls String(int offset,int count,char[] value).
Interesting thing here is that value[] array is the same character array used to represent the original String.
Main problem is that if Original String is very huge say 1GB, no matter how small the substring be it will be taken the space as 1GB.

If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...