LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 15

Finding the second largest value in one pass Answer, explanation & discussion

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

What is the output of the following Java program?

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

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links