How to use Java substring Method with 2 Examples


How to use Java substring Method with 2 Examples

How to use Java substring Method with 2 Examples

The substring method

The substring method of the String class is used to return a string that is the substring of the given string.

You have to specify where to start the substring within the given string. While it ends at the end of that string.

An example of substring

To make it clearer, see the example below:

“The Strings are supported in java by using String class”.substring (4)

It will return following new string:

“Strings are supported in java by using String class”

Note: The begin Index also includes spaces.

Syntax of substring

The syntax of substring Java method is:

Strex.substring(beginIndex,endIndex);

Where Strex is an instance of the String class.

The two parameters, beginIndex and endIndex, in Java substring method are the integers, to specify where to start and end in the given string.

A substring with beginIndex example

The example below uses the string’s substring method. We are using the same string, as shown above, to demonstrate the substring method. The beginIndex is given the value of 4 that will result in a new string as shown below:



Experience this online

The output will be:

Strings are supported in java by using String class

A substring example with beginIndex and endIndex parameters

The example below uses Java substring method of the String class. In that example, both start and end indices are given.

Java String substring



Experience this online

The output will be:

Strings are supported in java

As you can see in result string, the begingIndex value of 4 started the string from “The ” (including space) and ‘searched’ till 33 characters of the given string by using substring method.

Also see: Java String



Was this article helpful?