Obtaining Substrings from a String Object
String Methods
We've compiled some helpful String methods below.
![]() |
Methods that are part of the AP Computer Science A Java subset are denoted by the APCSA label. |
A complete list of String methods can be found in the String API.
String substring(int beginIndex)
This method returns
- a part of this
Stringstarting atbeginIndexand going to the end of thisString.
Your Turn
Let's try it in the Java Playground.
- Predict the value of
part. - Run the code to determine if your prediction is correct.
partis assigned the valueloves Java, since the 5th index is thel.
String substring(int beginIndex, int endIndex)
This method is similar to the substring method that takes only one parameters.
The method returns
- a part of this
Stringstarting atbeginIndexand ending at the index beforeendIndex. You can think of this it asbeginIndexis the first value to include andendIndexis the first index not to include.
Your Turn
Let's try it in the Java Playground.
- Predict the value of
part. - Run the code to determine if your prediction is correct.
partis assigned the valueloves, since the 5th index is thel. The 10th index is the space before theJ. This is the first index to not be included in the substring.
The value of endIndex can be the length of the string. Since the substring that is being created starts at beginIndex and the first index that is not included is endIndex, our call does not go out of bounds of the string.
Your Turn
Let's try it in the Java Playground.
- Predict the value of
part. - Run the code to determine if your prediction is correct.
partis assigned the valueloves Java, since the 5th index is thel. The 15th index is only one beyond the last index value. This is the first index to not be included in the substring.
A strategy that can be used to determine the substring between two indices is to draw a vertical line to the left of each index as illustrated below. The substring will be between these lines.
Complete List of String Learn Tutorials
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: String Indexing
- Learn: Comparing Strings with compareTo methods
- Learn: Comparing Strings with equals methods
- Learn: Creating Substrings
- Learn: Creaing a new String with the Case Changed
Resources
- Learn: Declaring Strings
- Learn: Introduction to Arithmetic Expressions
- Learn: Introduction to Console Input and Output
- Learn: Formatting Output with Escape Sequences and Text Blocks
- Practice: Evaluating Expressions that Use String Methods
- Practice: Write Code that Uses the String Methods
- Practice: AP Computer Science A String Free Response Questions