Question 4
Back to Exercise
What is the output of the following Java program?
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!