String methods – substring
As its name says, it is used to get the substring from the any String.
It has 2 types of implementations.
- String substring(int beginIndex)
- String substring(int beginIndex, int endIndex)
Let’s look at them one by on with examples.
String substring(int beginIndex):
It is used to return the substring starting from the specified index(beginIndex) till the end of the string.
e.g. Suppose, we have a string “”Hello World”. If we want to return a substring “world” then we have to do the following shown in the example below.
public class ExampSubstring { public static void main(String[] args) { String val1 = "Hello World"; System.out.println("Returns the substring - "+val1.substring(5)); // returns world } }
String substring(int beginIndex, int endIndex):
Returns the substring starting from the given index(beginIndex) till the specified index(endIndex).
public class ExampSubstring { public static void main(String[] args) { String val1 = "Hello World"; System.out.println("Returns the substring - "+val1.substring(3,8)); // returns world } }
IndexOutOfBoundsException,
If the beginIndex
is less than zero OR beginIndex > endIndex
OR endIndex
is greater than the length of String.
1 Response
[…] String substring(int beginIndex) […]