Sunday 22 June 2014

substring (int beginIndex)

public String substring(int beginIndex)
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

class StringSubString{
 public static void main(String args[]){
  String str = "Self Learning Java";
  String str1 = str.substring(0);
  String str2 = str.substring(5);
  String str3 = str.substring(14);
  
  System.out.println("str = " + str);
  System.out.println("str1 = " + str1);
  System.out.println("str2 = " + str2);
  System.out.println("str3 = " + str3);
 }
}

Output
str = Self Learning Java
str1 = Self Learning Java
str2 = Learning Java
str3 = Java

1. Throws IndexOutOfBoundsException if beginIndex is negative or larger than the length of this String object.

class StringSubStringIndexOut{
 public static void main(String args[]){
  String str = "Self Learning Java";
  String str1 = str.substring(-1);

  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:1914)
        at StringSubStringIndexOut.main(StringSubStringIndexOut.java:4)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment