20 October 2013

Difference between subSequence and substring in Java (CharSequence and String)

Hi all,

Lets see the two method in Java - subSequence and substring.

When we consider a string str = "Hello World.!!" and call these two method with same parameters they returns the same value.

class StringSeqSub
{
 public static void main(String args[])
 {
  String str = "Hello World.!!";
  System.out.println(str.substring(0,5));
  System.out.println(str.subSequence(0,5));  
 } 
}

When we execute the about code, we get the output
Output - 
Hello
Hello

Now question comes out if both return the same value why java developers provided two method if one method can fulfill the demand.??
Let see the signature of both methods.
public CharSequence subSequence(int beginIndex, int endIndex)
public String substring(int beginIndex, int endIndex)
now we can find return type is different in both cases.
class StringSeqSub
{
    public static void main(String args[])
    {
        String str = "Hello World.!!";
        // String s1 = str.subSequence(0, 5);    // this line will throw error
        CharSequence s1 = str.subSequence(0, 5);
        String s2 = str.substring(0, 5);
        System.out.println(s1);
        System.out.println(s2);
    } 
}
and again the output will be same
Output - 
Hello
Hello

Now lets see the basic difference between CharSequence and String class..
1. 'String'  is a class while on the other side 'CharSequence'  is interface.
2.  'String'  implements the 'CharSequence'  interface. CharSequence is implemented by String, but
     also CharBuffer, Segment, StringBuffer, StringBuilder.

3. String[] and a CharSequence[] is essentially the same. But CharSequence is the abstraction, and
    String is the implementation.

Now as in point 2 I told you 'String' implements the interface 'CharSequence' so we can hold the object of string in reference variable of CharSequence.
     CharSequence s1 = str.subSequence(0, 5);
     // String s1 = str.subSequence(0, 5);  // this line will throw error
     String s2 = str.substring(0, 5);
     CharSequence s3 = str.substring(0, 5); // this line will not throw error

for more details on this refer these link link1 and link2.

Happy knowledge sharing.. :)

No comments:

Post a Comment