Reading Substring in Java

A substring is a String object created from another String object. In Java, you can get substring in multiple ways based on which String class you are using. Classes like String, StringBuffer, StringBuilder have substring and subSequence methods which can return substring. One thing we have to remember is that the index of string start from 0.

Java is fun to learn


String.substring (index) returns part of the source string, starting from the index value passed till the end of the string. In the below example, character at index 8 is ‘f’. Since we are not passing end index, the substring begins with the passed index value and ends with the last character of the string.

String str1 = "Java is fun to learn";
fun to learn

If the index value is equal to the length of the string, substring method will return empty String object.

If the index value is less than 0 or greater than the length of the string, JVM throws StringIndexOutOfBoundsException.

String.substring(beginIndex, endIndex)

String.substring method contains two parameters. First parameter beginIndex defines the starting character index and the second parameter defines end index of the substring. However, the result string doesn’t comprise the character at end index. That means, when we pass these parameters, substring method returns part of the source string, starting from beginIndex to endIndex-1.

String str1 = "Java is fun to learn";
// Output

If end index is equal to the length of the string, it will print start index to entire string.

See also  Is Constructor Overriding Runtime Polymorphism in Java?

If start index is greater than end index, JVM will throw StringIndexOutOfBoundsException.

Similarly, if start index or end index is less than zero or greater than the length of the string, JVM will throw StringIndexOutOfBoundsException.

If the beginIndex and endIndex values are 0, substring method will return the same object upon which we’ve calledsubstring method.

String.subSequence(startIndex, endIndex)

String.subSequence method works similar to String.substring method. In fact, subSequence method calls substring internally.

How String.substring in Java works?

A substring method creates a new String object using its constructor String(char[] value, int offset, int count). Before creating the new String object it will check if beginIndex is greater than 0 and endIndex is less than the length of the current String, if not, it will throw StringIndexOutOfBoundsException.