LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 14

A static nested class used without an outer object Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    static class Pair {
        final String key;
        final int value;
        Pair(String k, int v) { key = k; value = v; }
        @Override public String toString() { return key + "=" + value; }
    }

    static Pair maxOf(Pair[] pairs) {
        Pair best = pairs[0];
        for (Pair p : pairs) if (p.value > best.value) best = p;
        return best;
    }

    public static void main(String[] args) {
        Pair[] ps = {new Pair("a", 3), new Pair("b", 9), new Pair("c", 5)};
        System.out.println(maxOf(ps) + " " + ps.length);
    }
}
  • A b=9 3 Correct
  • B a=3 3
  • C c=5 3
  • D Compilation error
Correct Answer: Option A

A static nested class can be instantiated directly from static code.

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