The problem begins at your do while loop.
Say arr.length() == 3 (so that means the loop should run 3 times, 0 < 3, 1 < 3, 2 < 3)
The problem is when it reaches the last time - it checks if 2 (n) is...