LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Predict the Output · Question 14

Returning this from setters Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
class Message {
    private String to = "", text = "";
    private int priority;

    Message to(String to) { this.to = to; return this; }
    Message text(String text) { this.text = text; return this; }
    Message urgent() { this.priority++; return this; }

    @Override public String toString() { return "[" + priority + "] " + to + ": " + text; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Message().to("Asha").urgent().text("Meeting at 5").urgent());
    }
}
  • A [2] Asha: Meeting at 5 Correct
  • B [1] Asha: Meeting at 5
  • C [0] Asha: Meeting at 5
  • D [2] :
Correct Answer: Option A

Each call returns the same object, so urgent() increments the same priority twice.

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