Why the error, if the output correctly Am Ham I Ham Sam Ham
public class Solution {
    public static void main(String[] args) throws Exception {
        BufferedReader a = new BufferedReader(new InputStreamReader(System.in));
        ArrayList<String> str = new ArrayList<>();
        str.add("Sam");
        str.add("I");
        str.add("Am");

        for (int i = 0; i < str.size(); i++) {
            str.add((i),"Ham");
            i++;
        }

        for (int i = str.size()-1; i >= 0; i--) {
            System.out.println(str.get(i));
        }
    }
}