LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 15

A setter that normalises input Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
class Contact {
    private String phone = "";

    void setPhone(String raw) {
        String digits = raw.replaceAll("\\D", "");
        if (digits.length() == 12 && digits.startsWith("91")) digits = digits.substring(2);
        if (digits.length() == 10) phone = digits;
    }

    String getPhone() { return phone.isEmpty() ? "(none)" : "+91 " + phone.substring(0, 5) + " " + phone.substring(5); }
}

public class Main {
    public static void main(String[] args) {
        Contact c = new Contact();
        String a = c.getPhone();
        c.setPhone("+91 (987) 654-3210");
        String b = c.getPhone();
        c.setPhone("12345");
        System.out.println(a + " | " + b + " | " + c.getPhone());
    }
}
  • A (none) | +91 98765 43210 | +91 98765 43210 Correct
  • B (none) | +91 (987) 654-3210 | 12345
  • C (none) | +91 98765 43210 | (none)
  • D | +91 98765 43210 | +91 12345
Correct Answer: Option A

The setter stores one clean format and ignores invalid numbers; the getter decides how to display it.

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