Getting a Substring from a String and an Index - Example 1
Snippet: Getting a Substring from a String and an Index
Explanation
This snippet introduces the single-argument form of substring(). Calling message.substring(6) extracts everything from index 6 to the end of the string. Since "Hello World!" has 'W' at index 6, the result is "World!".
String indexes in Java start at 0, so 'H' is at index 0, 'e' at index 1, and so on. The original message is not modified — substring() always returns a new string.
What You Can Do
Try changing the index to extract different parts of the string. What do you get with substring(0)? What about substring(12) — the index just past the last character?
You can also try using message.length() to compute the start index dynamically. For example, can you always extract just the last character, no matter how long the string is?
Run it and observe the output!
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