What will be the result of compiling and running the following program?

public class App1 {
    public static void main(String[] args) {
        System.out.println(addToString("12345678910",','));
    }

    public static StringBuffer addToString(String s, char c) {
        StringBuffer b = new StringBuffer(s);
        int p = 0;
        for (int i = 1; i < b.length(); i++) {
            if (i%3 == 0) {
                b.insert(b.length()-i-p, c); 
                p++;
            }
        }
        return b;
    }
}
Explanation
Keep in mind that the line changes dynamically:
i = 3 symbol is inserted into the 8-th position; as result b = "12345678,910", b.length() = 12
i = 6 symbol is inserted in the 5th position; as result b = "12345,678,910", b.length() = 13
i = 9 symbol is inserted into 2nd position; as result b = "12,345,678,910", b.length() = 14
i = 12 cycle continue being performed (as 12 < 14), the attempt is made to insert a symbol in the 1-th position and then the exception is thrown.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести