The Java String substring() method returns a new string that is a substring of this string. substring()
method is overloaded method and comes in two variants:
- String substring(int beginIndex)
- String substring​(int beginIndex, int endIndex)
Where method arguments are:
- beginIndex – the beginning index, inclusive.
- endIndex – the ending index, exclusive.
1. Java String substring(int beginIndex) example
It returns a string that is a substring of the string. The substring begins with the character at the specified 'beginIndex'
to the end of string.
- Please note that index starts from ‘0’ which refer to first character of String.
- Method will throw
StringIndexOutOfBoundsException
error if argument index is not a valid index. A valid index is always greater than or equal to zero; or less than or equal to the length of string.
0 >= Valid index <= length of string
Java program to get substring of a string from given index.
public class StringExample { public static void main(String[] args) { String blogName = "howtodoinjava.com"; System.out.println(blogName.substring(3)); //todoinjava.com System.out.println("hello world".substring(6)); //world } }
Program output.
todoinjava.com world
2. Java String substring(int beginIndex, int endIndex) example
It returns a string that is a substring of the string. The substring begins with the character at the specified 'beginIndex'
(included) to the 'endIndex'
(excluded) position.
Java program to get substring of a string from given start index to end index.
public class StringExample { public static void main(String[] args) { String blogName = "howtodoinjava.com"; System.out.println(blogName.substring(14, blogName.length())); //com System.out.println("hello world".substring(6,9)); //wor System.out.println("0123456789".substring(3, 7)); //3456 } }
Program output.
com wor 3456
In last statement, example makes more sense as each character represent it’s index position in the string. ‘0’ at 0th index, ‘1’ at first index and so on till ‘9’ at ninth position.
When we find a substring from index 3 to index 7, we get string ‘3456’. Begin index is included and end index ‘7’ got excluded.
Happy Learning !!
References:
Hey. Nice article. A small suggestion : as mentioned in the article ” The substring begins with the character at the specified ‘beginIndex’ to the ‘endIndex’ position.” You should also clarify that the ‘endIndex’ is excluded. As in, it is a [) behavior.
eg: in case of “hello world”.substring(6,9) “wor” is returned, and not “worl”.