String Methods


🙋 Need help? Ask an expert now!

In Java, a "Substring" is a string that is comprised from another string, and there are two methods by which one is made. Take a look at the example below that shows us both substring(int startIndex) and substring(int startIndex, int endIndex).
package exlcode;

public class SubStringExample {

  public static String exampleVariableOne = "Hello World!";
  // returns a String between the given indices and assigns
  // it to String variables
  public static String exampleVariableTwo = exampleVariableOne.substring(0, 5);
  public static String exampleVariableThree = exampleVariableOne.substring(6);

  public static void main(String[] args) {

The first method, substring(int startIndex) returns a new String containing the characters between "startIndex" and the final index of the called String, so the statement exampleVariableOne.substring(6) returns the entire string "World!". If the "startIndex" is equal to the total length of the string, an empty string is created.

The second method, substring(int startIndex, int endIndex) returns a new String made up of the characters beginning at the "startIndex" and ending at the "endIndex - 1". This method includes the first character and excludes the last character of the parameters entered. As long as both inputs are valid indexes of the String you won't throw a runtime error.

As discussed before, strings are immutable, so a new String is created every time you call either of the substring() methods.

Edit Me on GitHub!

Application Question