Tuesday, May 24, 2016

Difference between subsequence and substring in Java

Although we know that String.subSequence and String.subString methods produce the same output yet there are some differences in these methods . Also, we will go through the concept that why String has subSequence method at all when we have subString method.


1) Return Type :: String.subSequence(begin,end) method returns a CharSequence while String.subString(begin,end) returns the String reference. Although it does not make any difference to the end result and both will be same.
For Example:
String string = "Punia";
CharSequence subSequence = string .subSequence(0,2);
String subString = string .subString(0,2);

If we print the values of subSequence and subString, it will be Pu in both the cases. Hence the only difference is the return type. Below are the signatures of both:

public CharSequence subSequence(int beginIndex, int endIndex)
public String substring(int beginIndex, int endIndex)

2) Consecutivity : If we talk about the basics of these two concepts, Substrings are the consecutive combinations of the letters while subsequences are the non-consecutive combinations, like:

if "abc" is series of characters then ,

substrings: a, ab, abc, bc, c and the empty substring.
subsequences: a, b, ab, c, ac, bc, abc and the empty subsequence.


From the upper points , it is clear that there is no difference in usage of these two methods, So why the core team of java put the subsequence method in the methods list of Stirng class. Here is the reason.

String class implements the CharSequence interface. And, CharSequence interface have a method named subSequence, hence String must give the implementation of this method whether it's functionality is similar to the substring or not.

Although, it's a point of confusion that they could have avoided the substing(begin,end) method to be defined in the String class. The reason is, they could not stop the subsequence method to come in the class if they are implementing the CharSequence interface. Rather, they could stop themselves to put the substring(begin,end) mehtod in the String class. They could have defined other Substring methods with different parameters plus this subsequence method is dropping in from CharSequence interface. Might be a matter of thought.

No comments:

Post a Comment