.substring()
Published Feb 24, 2023Updated Oct 26, 2023
Contribute to Docs
The .substring()
method returns a part of the string from some starting index to an (optional) ending index. If an ending index is not provided, the substring will be from the starting index to the end of the original string.
Syntax
string.substring(startIndex);
string.substring(startIndex, endIndex);
.substring()
returns characters from startIndex
up to, but not including, the character at endIndex
.
If endIndex
is omitted, .substring()
returns characters from startIndex
to the end of the string.
If startIndex
and endIndex
are equal, .substring()
returns an empty string.
A StringIndexOutOfBoundsException
is thrown if any of the following are true:
startIndex
is greater thanendIndex
startIndex
is greater than the length of the original stringstartIndex
orendIndex
is negative
Example
The following example uses .substring()
to display a substring of a given string.
// Example.javapublic class Example {public static void main(String[] args) {String blurb = "Java is cool!";// Printing last 5 characters of blurbSystem.out.println(blurb.substring(blurb.length() - 5));// Printing first 4 characters of blurbSystem.out.println(blurb.substring(0, 4));}}
This produces the following output:
cool!Java
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours