Reputation: 181
I am working on this bit of code
public class SimpleStringTest {
public static void main(String args[])
{
String ints="123456789";
System.out.println(ints.concat("0").substring(ints.indexOf("2"),ints.indexOf("0")));
}
As per as my knowledge on java "When the multiple methods are chained on a single code statement, the methods execute from left to right" Then, Why is this bit of code throwing StringIndexOutOfBondsException?
Thanks in advance, GPAR
Upvotes: 0
Views: 152
Reputation: 48404
Because String
s are immutable.
By invoking concat
, you are not modifying ints
, you are creating a new String
.
Therefore by the time you invoke ints.indexOf("0")
, ints
is still equal to its former value and the indexOf
invocation returns -1
, which in turn will be the outer bound of your substring
.
Try a counter-example with a mutable CharSequence
such as StringBuilder
:
StringBuilder ints = new StringBuilder("123456789");
System.out.println(ints.append("0").substring(ints.indexOf("2"),ints.indexOf("0")));
Output
23456789
Upvotes: 4
Reputation: 16067
Because ints.indexOf("0")
is applied on the original String ints
(not the one you concatenate).
Since there is no "0" indexOf("0")
returns -1 and which throws the exception.
Your code is equivalent to this:
String ints="123456789";
int indexOne = ints.indexOf("2");
int indexTwo = ints.indexOf("0");
System.out.println(ints.concat("0").substring(indexOne, indexTwo));
Upvotes: 2