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
String starting at beginIndex and going to the end of this 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.
part is assigned the value loves Java, since the 5th index is the l.
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
String starting at beginIndex and ending at the index before endIndex. You can think of this it as beginIndex is the first value to include and endIndex is 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.
part is assigned the value loves, since the 5th index is the l. The 10th index is the space before the J. 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.
part is assigned the value loves Java, since the 5th index is the l. 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
Resources
Next Learn Tutorial