LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 4

A constructor storing the caller's array Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

What is the output of the following Java program?

Main.java
class Readings {
    private final int[] values;
    Readings(int[] values) { this.values = values; }          // no copy
    int max() { int m = values[0]; for (int v : values) m = Math.max(m, v); return m; }
}

public class Main {
    public static void main(String[] args) {
        int[] data = {12, 45, 30};
        Readings r = new Readings(data);
        int before = r.max();
        data[2] = 99;
        System.out.println(before + " " + r.max());
    }
}
  • A 45 99 Correct
  • B 45 45
  • C 99 99
  • D 30 99
Correct Answer: Option A

The object shares the caller's array, so changing data changes the object. this.values = values.clone() would prevent it.

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