String substring example
String substring method is used to get a part of String using the start and end index.
String had 2 substring methods.
1 2 3 | public String substring(int beginIndex) public String substring(int beginIndex,int endIndex) |
1.
String substring(int beginIndex) returns part of the String from the given start index till the end of the String.
If beginIndex is greater than the length of the String or is negative, then IndexOutOfBoundsException is thrown
2.
String substring(int beginIndex,int endIndex) returns part of the String from the given start index till the end Index that is specified.
If beginIndex is greater than the length of the String or is negative or is greater than endIndex, then IndexOutOfBoundsException is thrown.
If endIndex is greater than the length of the String or is negative or is less then beginIndex, then IndexOutOfBoundsException is thrown.
String substring example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.kscodes.sampleproject; public class StringSubstringExample { public static void main(String[] args) { String testStr1 = "I will be used for substring example"; String testStr2 = "This is a test for substring"; System.out.println("substring(int) for testStr1 ::" + testStr1.substring(10)); System.out.println("substring(int,int) for testStr2 ::" + testStr2.substring(5,15)); } } |
Output
1 2 | substring(int) for testStr1 ::used for substring example substring(int,int) for testStr2 ::is a test |