Gpar
Gpar

Reputation: 181

Multiple string method chained in single code

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

Answers (2)

Mena
Mena

Reputation: 48404

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

Upvotes: 4

user2336315
user2336315

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

Related Questions