LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 4

toString() used automatically Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
class Temperature {
    double celsius;
    Temperature(double c) { celsius = c; }

    @Override
    public String toString() { return celsius + "°C"; }
}

public class Main {
    public static void main(String[] args) {
        Temperature t = new Temperature(36.6);
        System.out.println(t);
        System.out.println("Body: " + t + "!");
        System.out.println(String.valueOf(t).length());
    }
}
  • A 36.6°C Body: 36.6°C! 6 Correct
  • B Temperature@1b6d Body: 36.6°C! 6
  • C 36.6°C Body: 36.6°C! 5
  • D 36.6 Body: 36.6! 4
Correct Answer: Option A

println and string concatenation call toString() automatically.

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