LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Predict the Output · Question 20

An immutable class with a static factory Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
final class Version {
    private final int major, minor;
    private Version(int major, int minor) { this.major = major; this.minor = minor; }
    static final Version INITIAL = new Version(1, 0);
    static Version parse(String s) { String[] p = s.split("\\."); return new Version(Integer.parseInt(p[0]), Integer.parseInt(p[1])); }
    Version bumpMinor() { return new Version(major, minor + 1); }
    Version bumpMajor() { return new Version(major + 1, 0); }
    @Override public String toString() { return major + "." + minor; }
}

public class Main {
    public static void main(String[] args) {
        Version v = Version.parse("2.7");
        System.out.println(Version.INITIAL.bumpMinor().bumpMinor() + " " + v.bumpMajor() + " " + v.bumpMinor() + " " + v + " " + Version.INITIAL);
    }
}
  • A 1.2 3.0 2.8 2.7 1.0 Correct
  • B 1.2 3.0 2.8 2.8 1.2
  • C 1.1 3.0 2.8 2.7 1.0
  • D 1.2 3.7 2.8 2.7 1.0
Correct Answer: Option A

Every "bump" returns a new Version; v and the INITIAL constant never change.

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