I have an arraylist and i wanted to print just 3 of it, whenever i add 3 or more elements it doesn't give me an error but whenever i add less than 3 it gives me this error?
Can somebody explain to me what's happening? and why is it giving me an error?
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.
The .size() gets you the size of the array, but you knew that already because you have it in your code.
Perhaps explain again what you're hoping to achieve? For lists with 3 or more elements you want to print the last 3 elements. For lists with less than 3 elements you want to do what?
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.