Question 5
Back to Exercise
What is the output of the following Java program?
import java.util.Arrays;
class Board {
private final char[] cells = "---".toCharArray();
public char[] getCells() { return cells.clone(); }
public void mark(int i) { if (cells[i] == '-') cells[i] = 'X'; }
}
public class Main {
public static void main(String[] args) {
Board b = new Board();
char[] copy = b.getCells();
copy[0] = 'O';
b.mark(1);
System.out.println(new String(b.getCells()) + " " + Arrays.toString(copy));
}
}
- A -X- [O, -, -] Correct
- B OX- [O, -, -]
- C -X- [O, X, -]
- D --- [O, -, -]
Correct Answer: Option A
The caller changed only its copy; mark changed the real board.
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!