How to use the Java substring method
Java’s substring method is used to extract a substring from a larger string. There are two different ways to use it, either separating the string from an index to the end or with a pre-defined beginning and ending index for the substring.
What is the Java substring method and how is it used?
In Java, characters, digits and special characters can be combined into a Java string. If you want to extract a specific subset from the larger string, you have several options. The method Java String.split() breaks an entire string down into its individual parts to, for example, give you a clearer overview of the string. The method substring()
takes that one step further and returns only the part of the string that you define. You can define which part of the string you want to extract using solely a start index or with both a start and end index. In this tutorial, we’ll introduce Java’s substring()
method in its different forms.
- 99.9% uptime
- PHP 8.3 with JIT compiler
- SSL, DDoS protection, and backups
How to use Java substring()
with beginIndex
As mentioned above, there are two ways to use Java’s substring()
method. The first only defines the starting point of the substring that you want to extract. It breaks up the string from that index to the last character of the string. Its syntax looks as follows:
To use substring()
, you’ll first enter the string that you want to extract the substring from. Then you use an integer to define where the substring should begin. You can view the output with the Java command System.out.println
. The method works inclusively, meaning that the character that is in the position of the index you enter will also be separated. If the value of beginIndex
is smaller than 0 or larger than the actual length of the string, you’ll get an error message.
Let’s look at a simple example to see how exactly substring()
works in Java. We’ll create a string and then extract a substring.
When you run the code, you’ll get the following output:
Of course that works just as well with digits:
Here is the output:
How to use substring()
with beginIndex
and endIndex
The second way to use Java’s substring()
method allows for more control over the resulting substring. You’ll not only specify the starting point of the substring but also an end point. The syntax looks as follows:
The beginIndex
is inclusive, and the endIndex
is exclusive. Let’s once again look at a simple example:
The output is:
You can also easily extract a substring from within a single word. In the next example, we’ll create a grocery list:
The new output will look as follows:
In our last example we’ll show a practical use case for Java’s substring()
method. Imagine that you’ve received customer data in a certain format. If you want to isolate just a part of that information, substring()
is perfect. Let’s look at the code:
Here is the output: