Question 12
Back to Exercise
What is the output of the following Java program?
public class Main {
public static void main(String[] args) {
int cap = 5, head = 3;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 7; i++) sb.append((head + i) % cap);
System.out.println(sb + " " + (0 - 1 + cap) % cap + " " + (-1 % cap));
}
}
- A 3456789 4 4
- B 3401234 4 4
- C 3401234 4 -1 Correct
- D 3401234 -1 -1
Correct Answer: Option C
Java's % keeps the sign of the left operand, so −1 % 5 is −1. To step backwards in a ring buffer add the capacity first: (i − 1 + cap) % cap.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!