LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 5

A getter returning a copy of an array Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links