I am so confused. I thought to use str.substring(1), str has to be at least 2 characters, otherwise there should be index of of bound. But when I typed in, Java doesn't give any error. Why?
Asked
Active
Viewed 58 times
-4
-
2The [official documentation](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-) shows a fine example of that behaviour: `"emptiness".substring(9)` returns `""` (an empty string) – E_net4 Dec 19 '17 at 10:37
-
Because an empty string is still a string. Given `String a = "x";`, then `a.substring(1)` is `""`. – T.J. Crowder Dec 19 '17 at 10:39
2 Answers
1
Read the Javadoc:
String java.lang.String.substring(int beginIndex)
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
Your beginIndex
is equal to the length of the String
, so no exception is thrown and an empty String
is returned.

Eran
- 387,369
- 54
- 702
- 768
0
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
It is legal to have the index equal to the length in order to return an empty string.

BOC
- 1,109
- 10
- 20