Wednesday, June 2, 2010

How Java substring works

If you think you are a Java String guru, what do you expect the output of this:

String x = "0123456789";
System.out.println(x.substring(4, 9));
System.out.println(x.substring(4, 3));
System.out.println(x.substring(4, 4));

The fact is:
// start at index 4 and return the characters up to and including the

// 9th position (index 8). So the output is "45678".
System.out.println(x.substring(4, 9));

// java.lang.StringIndexOutOfBoundsException: String index out of range: -1

System.out.println(x.substring(4, 3));

// I thought it would be out-of-bounds. But it's a empty string, WEIRD! isn't it.

System.out.println(x.substring(4, 4));

No comments: