Sunday 12 August 2012

Java Substring Example


This Java substring example describes how substring method of java String class can be used to get substring of the given java string object.

Java String class defines two methods to get substring from the given Java String object.


String substring(int beginIndex)


Returns a new 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.This method throws IndexOutOfBoundsException  if beginIndex is negative or larger than the length of this String object.


String substring(int beginIndex,int endIndex)
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.The method throws 
IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
 
See the example given below:








public class JavaSubstringExample {

 public static void main(String args[]) {

  String name = "Hello World";

  /**
   * This will print the substring starting 
   * from index 6
   **/
  System.out.println(name.substring(6));

  /**
   * This will print the substring starting from index
   * 0 upto 4 not 5.IMPORTANT : Here startIndex is inclusive
   * while endIndex is exclusive.
   **/
  System.out.println(name.substring(0, 5));

 }

}


The output is:


World
Hello

No comments:

Post a Comment