java string substring program

Java String substring() example program

In this tutorial let’s use Java String substring() method to solve a given problem. In this Java String substring() example program we are going to print a substring of all characters in the inclusive range from start to end-1.

Java String substring() example problem

java string substring program

Let’s say “S” is the given string and two indices “start” and “end“. And you need to print substring starting from start to end-1. Below is the java program to achieve the same.

For instance, the following is the sample input and output required to be tested with the program.

Sample Input

3            //start
6            //end

Sample Output


Solution: Java String substring()

Below is the Java String substring sample program for the above given requirement.

package com.sneppets.programming;

import java.util.*;

public class SubstringDemo {

	public static void main (String[] args) {
		Scanner in = new Scanner(;
		System.out.println("Please enter a string S = ");
		String S =;
		System.out.println("Please enter value for index start");
		int start = in.nextInt();
		System.out.println("Please enter value for index end");
		int end = in.nextInt();


Please enter a string S = 
Please enter value for index start
Please enter value for index end


Note,  java string substring() method returns a part of the string i.e., substring.  And when you pass “start” and “end” indices as arguments to the substring method, it includes start index but end index is exclusive. Hence the end index value “o” is not included in the resulted substring.


public String substring(int beginIndex, int endIndex)


beginIndex - the beginning index, inclusive.

endIndex   - the ending index, exclusive.

The substring method of String class returns a new string i.e., substring of the given string. The substring begins at the specified beginIndex and extends till the character at index endIndex – 1. Therefore does not include the character at index endIndex.

Therefore, you can say the length of the substring is nothing but endIndex-beginIndex.

You’ll also like:



Inline Feedbacks
View all comments