Java String subSequence
Below code snippet is from String subSequence method implementation.
1 2 3 4 5 |
public CharSequence subSequence(int beginIndex, int endIndex) { return this.substring(beginIndex, endIndex); } |
String subSequence method returns a character sequence that is a subsequence of this sequence. An invocation of this method of the form str.subSequence(begin, end)
behaves in exactly the same way as the invocation of str.substring(begin, end)
.
Below is a simple Java String subSequence method example.
StringSubsequence.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.journaldev.examples; public class StringSubsequence { /** * This class shows usage of String subSequence method * * @param args */ public static void main(String[] args) { String str = "www.journaldev.com"; System.out.println("Last 4 char String: " + str.subSequence(str.length() - 4, str.length())); System.out.println("First 4 char String: " + str.subSequence(0, 4)); System.out.println("website name: " + str.subSequence(4, 14)); // substring vs subSequence System.out.println("substring == subSequence ? " + (str.substring(4, 14) == str.subSequence(4, 14))); System.out.println("substring equals subSequence ? " + (str.substring(4, 14).equals(str.subSequence(4, 14)))); } } |
Output of the above String subSequence example program is:
1 2 3 4 5 6 7 |
<span style="color: #008000;"><strong><code> Last 4 char String: .com First 4 char String: www. website name: journaldev substring == subSequence ? false substring equals subSequence ? true </code></strong></span> |
There is no benefit in using subSequence
method. Ideally, you should always use String substring method.