Getting a Substring from a String, a Begin Index and an End Index - Example 2
Snippet: Getting a Substring from a String, a Begin Index and an End Index
Explanation
This snippet introduces the two-argument form of substring(). Calling message.substring(0, 5) extracts characters from index 0 (inclusive) to index 5 (exclusive), giving "Hello".
The start index is inclusive and the end index is exclusive — so the character at index 5, which is ' ' (the space), is not included. This convention is consistent across Java: ranges typically include the start and exclude the end.
What You Can Do
Try extracting "World" from the same string. Which indexes would you use? Remember that the end index is exclusive.
You can also try extracting a single character using substring() — for example, message.substring(4, 5). What does it give you?
Example List
Additional Resources
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis