Hit enter after type your search item

How to get sub-strings by using Java substring function

The substring method of Java String class

In the string class chapter of Java, we learned how to create strings in Java along with a few useful functions of String class. One of the useful methods of the String class is substring().

What is substring method?

The substring is part of the source string that you may get by using the substring() method. In the Java substring method, you may specify the starting and end position in the source string as integer values. The position or index of a string starts at 0. So, if you want to get the substring “tutorial” from the following string, this is how substring() method can be used:

The source string: “This is Java substring tutorial!”

The substring method will be:

Str_substring.substring(23,31)

Where the Str_substring is the source string object. The value 23 tells to start the returned substring from letter “t” and end at 31 character in the string.

Have a look at this demonstration in a complete Java program below.

A demo of using substring Java method

Click the link to see the code and output to get the “tutorial” substring by using the substring() method:

Java code:


Output:

Java substring

A demo of using only starting index in substring Java method

In above example, I used both starting and end indices to get the substring. However, the end index in not required. In that case, the returned substring will be the remaining characters including the begin Index character in the string.

FYI, the left value is for starting index that includes the character in the string.

The right value is the ending index position that does not include the character.

See this example where I used only the starting index for the same string as in above example. See the code and output:

The code with starting index only:


Output:

substring begin index

What if starting index is greater than string length?

If you specify the starting index greater than the string length in string’s substring method, an error will generate. The error looks something like this:

Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: -1

See this example’s code where string length is 22. I used 23 starting index in the substring method and see the output:

The code:


Rersult:

substring error

So, as using the substring method beware of this exception.

This div height required for enabling the sticky sidebar