Extracting Substrings from Strings in Java

Class String provides Substrings methods to allow a new String object to be build by copying part of an current String object . Each method returns a new String object.

letters.substring (20)


With the use of Substring method that takes one integer argument. This point specifies the starting  index from which characters are copied in the  orginal String . The substring exchanged contains a copy of the character from the starting index to the end of the String . If the index specified as an argument is outside the bounds of the String, a StringIndexOutOfBoundException is generated.

The Substring method that takes two interger arguments.

1. The first  point determine that from the starting index from which character are copied in the original String.

2. The second point determine that the index one outside from  the last character to be copied.The substring exchange copies of the special character from the original String. If  the argument are outside the range of the string ,a StringIndexOutOfBoundsException is generated.

public class substring {
 public static void main(String args[]) {

  String letters = "Hello Student this is devstudioonline";
  String output;
  //test substring methods
  output = "Substring from index 20 to end is " + "\"" + letters.substring(20) + "\"\n";
  output += "Substring from index 0 up to 6 is " + "\"" + letters.substring(0, 6) + "\"";

  System.out.println(output);
 }
}

Output
Substring from index 20 to end is "s devstudioonline"
Substring from index 0 up to 6 is "Hello "


Keywords: