Skip Top Navigation Bar

Getting a Substring from a String, a Begin Index and an End Index - Example 3

Snippet: Getting a Substring from a String, a Begin Index and an End Index

Explanation

This snippet continues with the two-argument form of substring(), this time extracting a word from the middle of the string. Calling message.substring(6, 11) extracts characters from index 6 (inclusive) to index 11 (exclusive), giving "World" — without the trailing "!".

The character at index 11 is '!', and since the end index is exclusive, it is not included in the result. This shows how precise you can be with substring() — you can extract exactly the characters you want.

What You Can Do

Try extracting just the "!" at the end. Which indexes would you use? You can check your answer with both the one-argument and two-argument forms of substring().

You can also try combining the two substrings from this snippet and the previous one — hello + " " + world — and compare it to message.substring(0, 11). Are they equal?

Run it and observe the output!

Example List

Additional Resources