Java String Handling

Java String substring example

Java String substring example shows how to get substring from String in Java. Example also shows how to find substring in string and then get substring.

How to get substring from String in Java?

Java String class provides two versions of substring method to get substring from String as given below.

This method returns a new string containing substring starting from the startIndex till the length of the String.

This method returns a string containing substring starting from the startIndex till endIndex-1. Length of the returned substring is always equal to endIndex – startIndex.

Consider below given String object.

If you want to extract “string substring example” from the string, you can use substring method like given below.

Output

We specified only start index parameter to the substring method. So substring method will return a string containing substring starting from index 5 till string length, which in our case is “Substring Example”.

What if you want to extract “Java” from the String object given above? You need to specify both start and end index of the String. “Java” starts from index 0 and goes till index 3. Let’s try to extract it using substring method.

Output

Well, the output is not what we had expected. Instead of getting “Java”, we got only “Jav”. That is because, when you use substring method, start index is inclusive (included in the substring) but the end index is exclusive (not included in the substring). So when we specified index 0 to index 3, substring started from index 0 but ended on index 2, thus giving us only “Jav”. Below given is the correct program.

Output

How to find substring in String in Java?

How do I know from where to start getting the substring if the String content is not known? You need to find substring in string to get the start index and/or end index in that case. You can find substring in string using indexOf and lastIndexOf methods.

Consider below given string.

How to extract file name from the path? You can search the last index of “/” and start taking substring from there till the end of the string as given below.

Output

We added 1 to the last index of “/” because we did not want to include “/” in the substring.

Getting StringIndexOutOfBoundsException while getting the substring?

substring method throws StringIndexOutOfBoundsException in below given cases.

1) If start index is negative
2) If start index is greater than the string’s length
3) If end index is specified and it is greater than the string’s length
4) If end index is specified and start index is greater than end index

For example,

Output

You should always check the start and end index parameters to avoid getting the StringIndexOutOfBoundsException exception.

Please let us know your views in the comments section below.

 

Tags
Join 1000+ fellow learners! Enter your email address below: