substring index range

Upvote picture Upvote · Dec 31, 2010 · Viewed 155k times · Source

Code:

public class Test {
    public static void main(String[] args) {
        String str = "University";
        System.out.println(str.substring(4, 7));
    }   
}

Output: ers

I do not really understand how the substring method works. Does the index start at 0? If I start with 0, e is at index 4 but char i is at 7 so the output would be ersi.

Answer

Axel Fontaine picture Axel Fontaine · Dec 31, 2010

0: U

1: n

2: i

3: v

4: e

5: r

6: s

7: i

8: t

9: y

Start index is inclusive

End index is exclusive

Javadoc link