This probably has a very obvious answer, but I just started learning Java and discovered this.
Say we have
String x = "apple";
Why is it that x.substring(5)
returns ""
, an empty string while x.substring(6)
throws an IndexOutOfBounds
exception? Is there some kind of empty string that can be referenced appended to every string? Just not sure how it works.
Thanks!
The substring(int beginIndex, int endIndex) method of the String class. It returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Strings in Java are immutable. Basically this means that, once you create a string object, you won't be able to modify/change the content of a string.
The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string. If start is greater than end, arguments are swapped: (4, 1) = (1, 4). Start or end values less than 0, are treated as 0.
In the String object, when you call substring , the value property is shared between the two strings. So, if you get a substring from a big string and keep it for a long time, the big string won't be garbage collected. It could result in a memory leak, actually.
Javadoc says for public String substring(int beginIndex)
:
"Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex."
The length of "apple" is 5, so the length of x.substring(5)
is 5 - 5 == 0.
On the other hand the api doc says that if
"... endIndex is larger than the length of this String object ..." the exception you experienced is thrown. For x.substring(6)
your endIndex is 6 while the length of the String object is 5.
You are asking "Is there some kind of empty string that can be referenced appended to every string?". I would say yes, that's true in some way: the empty string is 'contained' at any position of any string, and it can be appended to any string without changing it. But I'm not sure if this way of viewing it helps...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With