Skip Top Navigation Bar

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