Question 15
Back to Exercise
What is the output of the following Java program?
public class Main {
public static void main(String[] args) {
int[] a = {12, 35, 1, 35, 10, 34};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : a) {
if (x > first) {
second = first;
first = x;
} else if (x > second && x != first) {
second = x;
}
}
System.out.println(first + " " + second);
}
}
- A 35 34 Correct
- B 35 35
- C 34 35
- D 35 12
Correct Answer: Option A
x != first stops a duplicate of the maximum from becoming the second largest.
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!