Trusted answers to developer questions

How to get a substring in Java

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

The substring() method in Java returns a portion of a string and is used to get substrings in java.

There are two variants for the substring() method implementation​ in Java.

Variant 1

We specify a start index and the returned substring includes​ characters starting from the specified start index, of the input string, until the end of the string.

stringName.substring(int startIndex)

A visualization​ of this is shown below:

1 of 3
class HelloWorld {
public static void main( String args[] ) {
String str="edpresso";
System.out.println( str.substring(2) );
}
}

Variant 2

We specify the start index and the end index, ​and the returned substring includes characters including and between the specified indexes. The character at the start index is included, but the character at the end index is not included while getting the substring. So, the characters in the extracted substring begin from start index to end index-1

stringName.substring(int startIndex, int endIndex)

A visualization​ of this is shown below:

1 of 3
class HelloWorld {
public static void main( String args[] ) {
String str="edpresso";
System.out.println( str.substring(2,7) );
}
}

Note: substring() method does not change the original string.

Application of substrings

Substring extraction is useful for prefix and suffix extraction. For example, it is helpful in extracting the family name from a name.

RELATED TAGS

substring
java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?