Pages

Monday, December 21, 2020

Java String subSequence() Examples - Print subSequence in String

1. Overview


In this article, You'll learn how to get the subsequence from a String. This looks similar to the java string substring() method but the substring method returns a new String but subSequence method returns CharSequence rather than String.

Java String subSequence() Examples - Print subSequence in String


2. String subSequence() Syntax


Let us see the syntax from String api.
public CharSequence subSequence​(int beginIndex, int endIndex)
This method takes two parameters and those are begin and start index.

Returns a CharSequence for the given indexes. These two indexes should be in between the 0 and length of the string.

If the indexes are outside the limits then it will throw IndexOutOfBoundsException.

What will happen if the index is negative? Negative indexes are not supported in java as in python. So, it will produce the runtime exception IndexOutOfBoundsException.

3. String subSequence() Example

package com.javaprogramto.strings;

public class StringsubSequenceExample {

    public static void main(String[] args) {

        String stringObject = "javaprogramto.com is a java blog";

        CharSequence output1 = stringObject.subSequence(20, stringObject.length());
        System.out.println(output1);

        CharSequence output2 = stringObject.subSequence(0, 18);
        System.out.println(output2);

    }
}

Output:
 a java blog
javaprogramto.com 

4. String subSequence() With Negative Example


Let us pass the negative index and see how it works at runtime.
package com.javaprogramto.strings;

public class StringsubSequenceWithNegativeExample {

    public static void main(String[] args) {

        String stringObject = "This example is with negative index";

        CharSequence output = stringObject.subSequence(-10, stringObject.length());
        System.out.println(output);
    }
}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin -10, end 35, length 35
	at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
	at java.base/java.lang.String.substring(String.java:1874)
	at java.base/java.lang.String.subSequence(String.java:1913)
	at com.javaprogramto.strings.StringsubSequenceWithNegativeExample.main(StringsubSequenceWithNegativeExample.java:9)

5. Differences between substring() and subSequence()


substring() method returns String and other subSequence() method returns CharSequence. The main thing is that you can not pass the single start index as like to the substring() method. And also subSequence() internal implementation is based on the substring() method.

6. Conclusion


In this article, You've seen how to use the subSequence() from String API. This method internally calls the substring() method so it is better to go with the substring() method.

All examples are over the GitHub

No comments:

Post a Comment

Please do not add any spam links in the comments section.