Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the java substring method work like this? [duplicate]

Tags:

java

string

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!

like image 635
qwert Avatar asked Mar 25 '16 02:03

qwert


People also ask

How does the substring method in Java work?

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.

Does substring in Java change the original string?

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.

What is the purpose of the substring () method and how do you use it?

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.

How does substring cause memory leak?

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.


1 Answers

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...

like image 136
yaccob Avatar answered Sep 26 '22 20:09

yaccob