LearnFrenzy
Sign in Take a free test

Methods and Recursion · Predict the Output · Question 16

Early returns from a method Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    static String classify(int n) {
        if (n < 0) return "negative";
        if (n == 0) return "zero";
        if (n % 2 == 0) return "even";
        return "odd";
    }

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int n : new int[]{-3, 0, 4, 9}) sb.append(classify(n).charAt(0));
        System.out.println(sb);
    }
}
  • A nzeo Correct
  • B nzoe
  • C neeo
  • D zneo
Correct Answer: Option A

Each return leaves the method immediately, so later checks run only for numbers that passed the earlier ones.

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