Java puzzle 12: Passing parameters to 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 
>

In this Java puzzle we pass a parameter to a constructor. I congratulate you if you can solve this puzzle!

Java puzzle 12: Passing a parameter to a constructor

Level: Hard

What is the output of this program and why?

public class MyClass
{
  int x = 7;
  
  public MyClass()
  {
    x++;
    System.out.print(" n" + x);
  }
  public MyClass(int i)
  {
    x += i;
    System.out.print(" p" + x);
  }
  public int method(int i)
  {
    x += i;
    System.out.print(" s" + x);
    return x;
  }
  public static void main(String[] args)
  {
    new MyClass(new MyClass().method(3));
  }
}
Author: Sar Maroof

Answer explanation

  1. The statement new MyClass().method(3); instantiates an object from the class MyClass using the no-argument constructor.
    The statement x++; increments the value of x by 1, x = 7+ 1 = 8. The statement System.out.print(” n” + x); writes n8 to the standard output.
  2. The statement new MyClass().method(3) invokes the method and passes the value 3 to it. By passing the value 3, the statement x += i; increments the value of x by 3. The last value of x was 8. So, x = 8 + 3 = 11.
    The statement System.out.print(” s” + x); writes s11 to the standard output.
  3. The method method(3) returns 11 and we pass that value to a new object by using the statement new MyClass(new MyClass().method(3));
    new MyClass(11) creates an object using the one-argument constructor.
    The statement x += i; increments the value of x by i.
    Don’t forget that this is a new object that is why the value of x is 7 + 11 = 18.
    The statement System.out.print(” p” + x); writes p18 to the standard output.

The correct answer is: This program writes n8 s11 p18 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

Your email address will not be published. Required fields are marked *