Skip Top Navigation Bar

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