Skip to Content

Substring Example

  1. /*
  2. Java substring example.
  3. This Java substring example describes how substring method of java String class can
  4. be used to get substring of the given java string object.
  5. */
  6.  
  7. public class JavaSubstringExample{
  8.  
  9.   public static void main(String args[]){
  10.  
  11.   /*
  12.   Java String class defines two methods to get substring from the given    
  13.   Java String object.
  14.  
  15.   1) public String substring(int startIndex)
  16.   This method returns new String object containing the substring of the
  17.   given string from specified startIndex (inclusive).
  18.   IMPORTANT : This method can throw IndexOutOfBoundException if startIndex
  19.   is negative or grater than length of the string.
  20.  
  21.   2) public String substring(int startIndex,int endIndex)
  22.   This method returns new String object containing the substring of the
  23.   given string from specified startIndex to endIndex. Here, startIndex is
  24.   inclusive while endIndex is exclusive.
  25.   IMPORTANT: This method can throw IndexOutOfBoundException if startIndex
  26.   is negative and if startIndex of endIndex is grater than the string length.
  27.   */
  28.  
  29.   String name="Hello World";
  30.  
  31.   /*
  32.   This will print the substring starting from index 6
  33.   */
  34.   System.out.println(name.substring(6));
  35.  
  36.   /*
  37.   This will print the substring starting from index 0 upto 4 not 5.
  38.   IMPORTANT : Here startIndex is inclusive while endIndex is exclusive.
  39.   */
  40.   System.out.println(name.substring(0,5));
  41.  
  42.   }
  43.  
  44. }
  45.  
  46. /*
  47. OUTPUT of the above given Java substring Example would be :
  48. World
  49. Hello
  50. */