Java String Substring

The substring() method in Java returns the substring of the given string. You can pass indexes from which position the substring should be started and ended. The substring() method in Java has two variants. In this tutorial, you will learn both variants with examples.

Substring method variants

Following are the two variants of the substring method:

  • Pass only start index
  • Pass both start and end index

Pass only start index

By using this variant of the method you can only pass the start index. So this method will return substring which starts from the given index and ends with the last index of string.

String substring(int startIndex)

Pass both start and end index

By using this variant of the method you can pass both start index and end index to get the substring. So this method will return substring which starts from given startIndex and ends with endIndex.

String substring(int startIndex,int endIndex)

Examples

Example 1

Following is the example for pass start index only substring() method variant.

The output for the above program should be:

The given string is:
This is New York City
Substring starting from index 5:
is New York City
Substring starting from index 8:
New York City
Substring starting from index 12:
York City
Substring starting from index 17:
City

Example 2

Following is the example for pass both start index and end index substring() method variant.

The output for above program should be:

substring(0,3) : New
substring(4,8) : York
substring(9,13) : City
substring(0,8) : New York
substring(4,13) : York City

LEAVE A REPLY

Please enter your comment!
Please enter your name here