0

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

2 Answers 2

4

Because Strings 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
Sign up to request clarification or add additional context in comments.

Comments

2

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.