substring() in Java

Java String Tutorial

Thu Jan 13, 2022

substring() method of String in Java

substring()

substring() method returns a part of the string.

Signature

public String substring(int startIndex)

public String substring(int startIndex, int endIndex)

If we don't specify endIndex, it will return all the characters from startIndex to end.

startIndex : starting index is inclusive

endIndex : ending index is exclusive

StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.

· if the start index is negative value

· end index is lower than starting index.

· Either starting or ending index is greater than the total number of characters present in the string.

String S1="Welcome";

System.out.println(S1.substring(3));

System.out.println(S1.substring(3,6));

System.out.println(S1.substring(3,7));

Output:

come

com

come

S P SHARMA CLASSES
S P SHARMA SIR

Launch your GraphyLaunch your Graphy
100K+ creators trust Graphy to teach online
𝕏
S P SHARMA CLASSES 2024 Privacy policy Terms of use Contact us Refund policy