LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Predict the Output · Question 18

Constants in an interface-free constants class Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following Java program?

Main.java
final class Http {
    private Http() { }
    static final int OK = 200, NOT_FOUND = 404, SERVER_ERROR = 500;

    static String describe(int code) {
        if (code == OK) return "success";
        if (code >= 500) return "server problem";
        if (code >= 400) return "client problem";
        return "other";
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Http.describe(Http.OK) + ", " + Http.describe(Http.NOT_FOUND) + ", " + Http.describe(Http.SERVER_ERROR + 3) + ", " + Http.describe(301));
    }
}
  • A success, client problem, server problem, other Correct
  • B success, server problem, server problem, other
  • C success, client problem, other, other
  • D Compilation error
Correct Answer: Option A

Named constants make the code readable; for a fixed set of values an enum is even better.

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