LearnFrenzy
Sign in Take a free test

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

A "constructor" with void Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
class Book {
    String title = "untitled";
    void Book() { title = "Java"; }        // looks like a constructor, but it is a method
}

public class Main {
    public static void main(String[] args) {
        Book b = new Book();
        System.out.print(b.title + " ");
        b.Book();
        System.out.println(b.title);
    }
}
  • A untitled Java Correct
  • B Java Java
  • C untitled untitled
  • D Compilation error
Correct Answer: Option A

With a return type it is an ordinary method that happens to share the class name; new uses the default constructor. (Legal, but a terrible idea.)

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