Java puzzle 08: Calling constructors within constructors

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 

Sometimes, you need to call a constructor within another constructor. Here is an example of how to do that. Try to use a pen and a paper to write notes if you can’t follow all the procedure in your mind clearly.

What is the output of this program and why?

Java puzzle 08: Calling constructors within other constructors

Level: Hard

public class MyConstructor
  String x = "f";
  String y = "g";
  MyConstructor(String str)
    this("d", "e");
    this.x = str;
  MyConstructor(String str, String str2)
    this.y = str2;
    System.out.print(x + "" + y);
  public static void main(String[] args)
    MyConstructor mc = new MyConstructor();
Author: Sar Maroof

Answer explanation

  1. By creating the object mc of MyConstructor, the no-argument constructor of the class is called.
  2. The no-argument constructor calls the one-argument constructor.
  3. The one-argument constructor calls the two-argument constructor.
  4. In the block of the two-argument constructor, the value of the x remains the initial value of x, which is f.
  5. In the block of the two-argument constructor, the value of the parameter str2 is assigned to the instance variable y.
  6. In the block one-argument constructor, we passed the values d and e to the two-argument constructor.
  7. So, the statement System.out.print(x + “” + y); writes fe to the standard output.
  8. The second statement in the block one-argument constructor this.x = str assigns the value of c to the variable x. Therefore the statement System.out.print(x); writes c to the standard output.
  9. At last in the no-argument constructor block the statement System.out.print(“a”); writes the letter a to the standard output.
    The correct answer is that this program writes feca to the standard output.

Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply