.substring()
Published Aug 22, 2022
Contribute to Docs
The .substring()
method returns a String
object representing a substring of the character sequence currently in a given StringBuilder
.
Syntax
myStringBuilder.substring(start, end);
The .substring()
method will return the substring starting at the zero-indexed int
start
index to the character specified at index end
- 1. If the int
end
is omitted, the substring will extend from start
to the end of the sequence. If start
or end
is negative, greater than the length of the StringBuilder
, or start
is greater than end
, a StringIndexOutOfBoundsException
is thrown.
Example
The following example creates a StringBuilder
with a specified String
and displays a substring from it.
import java.util.*;public class Example {public static void main(String[] args){StringBuilder str = new StringBuilder("Hello World!");System.out.println(str.toString());String s1 = str.substring(6,11);System.out.println(s1);}}
This produces the following output:
Hello World!World
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