I get exception Exception in thread \"main\" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 for the below code. But couldn\'t understand why.
Exception in thread \"main\" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
Your ArrayList is empty. With this line:
ArrayList
s.add(1,"Elephant");
You are trying to add "Elephant" at index 1 of the ArrayList (second position), which doesn't exist, so it throws a IndexOutOfBoundsException.
"Elephant"
1
IndexOutOfBoundsException
Use
s.add("Elephant");
instead.