What is a sub string in Java?


The String class of the java.lang package represents set of characters. All string literals in Java programs, such as "abc", are implemented as instances of this class. A string index is an integer representing the position of each character in the string starting from zero.

A substring is a part/segment of a string. You can identify a substring of a string using the substring() method of the String class. This method have two variants −

substring(int beginIndex)

This method accepts an integer value representing an index in the current string and returns the substring starting from the given index to the end of the string.

Example

Live Demo

import java.util.Scanner;
public class SubStringExample {
   public static void main(String[] args) {
      System.out.println("Enter a string: ");
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();  

      System.out.println("Enter the index of the substring: ");
      int index = sc.nextInt();          
      String res = str.substring(index);
      System.out.println("substring = " + res);
   }
}

Output

Enter a string:
Welcome to Tutorialspoint
Enter the index of the string:
11
substring = Tutorialspoint

substring(int beginIndex, int endstring)

This method accepts two integer values representing the index values of the current string and returns the substring between the given index values.

Example

Live Demo

import java.util.Scanner;
public class SubStringExample {
   public static void main(String[] args) {
      System.out.println("Enter a string: ");
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();  
      System.out.println("Enter the start index of the substring: ");
      int start = sc.nextInt();      
      System.out.println("Enter the end index of the substring: ");
      int end = sc.nextInt();  
      String res = str.substring(start, end);
      System.out.println("substring = " + res);
   }
}

Output

Enter a string:
hello how are you welcome to Tutorialspoint
Enter the start index of the substring:
10
Enter the end index of the substring:
20
substring = are you we

Updated on: 05-Feb-2021

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements