Your for loop is accessing the last 3 elements in the ArrayList. You are right in that the last element index of a list sized n, is index n - 1. So you know the index range for a list of size n is 0 ... n-1.
Think about the indexes you are trying to access for a list of size 2. Can you see what the problem with that is when you attempt to access the last 3 elements of a 2 element list? The ArrayIndexOutOfBoundsException will tell you the invalid index you are attempting to access, which may help you figure it out.
Tim Driven Development
posted 3 years ago
I understand.. Is there a way i could get the current size of the arraylist?
The code you presented will print the last 2 (not 3) elements in the list. And it runs fine unless the array size is 0 or 1. In order to handle those scenarios you can modify the termination clause, as I already talked about.