Page 1 of 1
About Question enthuware.ocajp.i.v7.2.1185 :
Posted: Mon Sep 28, 2015 11:53 am
by troydh53
The explanation says: "emptiness".substring(9) returns "" (an empty string). And that's correct. I would have expected an error because there are only 8 elements to the string. Why doesn't it throw a StringIndexOutOfBounds error?
Re: About Question enthuware.ocajp.i.v7.2.1185 :
Posted: Mon Sep 28, 2015 7:17 pm
by admin
Because of the way substring method has been designed. As per its JavaDoc API, it throws an IndexOutOfBoundsException only if beginIndex is negative or larger than the length of this String object. The length of the given string is 9. So substring(9) will not throw an exception.
There is no special reason here. It is just the way they designed this method to work.
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1185 :
Posted: Wed Dec 02, 2015 5:58 pm
by deniscapeto
why does the StringBuilder sb is modified by "blooperper".delete(3, 5) if the code ignored the return?
the correct answer wouldn´t be "blooperper"?
or the code could be:
sb = sb.append(s.substring(4)).delete(3, 5);
StringBuilder isn´t immutable like String?
Re: About Question enthuware.ocajp.i.v7.2.1185 :
Posted: Wed Dec 02, 2015 8:31 pm
by admin
No, StringBuilder (and StringBuffer) is not immutable.
I am not sure why you feel that the code ignoring the return value is important. The StringBuilder object on which you called delete(3,5) has already been changed by the delete method. The method returns the reference to the same StringBuilder object (which has now been changed internally). Now, whether you use the return value or not is immaterial.
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1185 :
Posted: Thu Dec 03, 2015 8:24 am
by deniscapeto
Thanks Paul,
I thought delete method on StringBuilder worked like String, so the return would be important. Now it´s clarified.