String Objects: Concatenation, Literals, and More

AP Computer Science A· difficulty 3/5

public static String run() {
    String r = "";
    for (int i = 1; i <= 4; i++) {
        if (i % 2 == 0) r = i + r;
        else r = r + i;
    }
    return r;
}
// Call: System.out.println(run());

What is printed?

  • A

    1234

  • B

    4321

  • C

    1324

  • D

    4213

    check_circle

Explanation

i=1 (odd): r="1". i=2(even): r="21". i=3(odd): r="213". i=4(even): r="4213".

Want 10 more like this — adaptive to your weak spots?

Related questions