java - Multiple string method chained in single code -



java - Multiple string method chained in single code -

i working on 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 knowledge on java "when multiple methods chained on single code statement, methods execute left right" then, why bit of code throwing stringindexoutofbondsexception?

thanks in advance, gpar

because strings immutable.

by invoking concat, not modifying ints, creating new string.

therefore time invoke ints.indexof("0"), ints still equal former value , indexof invocation returns -1, in turn outer bound of substring.

try counter-example mutable charsequence such stringbuilder:

stringbuilder ints = new stringbuilder("123456789"); system.out.println(ints.append("0").substring(ints.indexof("2"),ints.indexof("0")));

output

23456789

java string

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -