Sunday 22 June 2014

subSequence (int beginIndex, int endIndex)

public CharSequence subSequence(int beginIndex, int endIndex)
Returns a character sequence that is a subsequence of this sequence. The character sequence begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

class StringSubSequence{
 public static void main(String args[]){
  String str = "Self Learning Java";
  CharSequence str1 = str.subSequence(5, 14);
  
  System.out.println("str = " + str);
  System.out.println("str1 = " + str1);
 }
}

Output
str = Self Learning Java
str1 = Learning

1. Throws IndexOutOfBoundsException, if beginIndex or endIndex is negative, if endIndex is greater than length(), or if beginIndex is greater than endIndex
class StringSubSequenceIndexOut{
 public static void main(String args[]){
  String str = "Self Learning Java";
  CharSequence str1 = str.subSequence(15, 14);
  
  System.out.println("str = " + str);
  System.out.println("str1 = " + str1);
 }
}

Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
        at java.lang.String.substring(String.java:1954)
        at java.lang.String.subSequence(String.java:1990)
        at StringSubSequenceIndexOut.main(StringSubSequenceIndexOut.java:4)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment