Java puzzle 20: Classes and 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 
>

If this code is compiled and run, it writes nullx2 to the standard output. Write only one statement at line 8. As a result of your statement the program writes xx3 to the standard output. What is that statement?

Java puzzle 20: Classes and constructors

Level: Normal

public class MyClass
{
  String str;
  int i;
  
  MyClass()
  {
    // add your statement here!
    i += 2;
    str += "x";
  }
  MyClass(String str, int i)
  {
    this.i = i;
    this.str = str;
  }
  public static void main(String[] args)
  {
    MyClass mc = new MyClass();
    System.out.print(mc.str + mc.i);
  }
}
Author: Sar Maroof

Answer explanation

  1. The statement should assign values to the variable i and the str object.
  2. To assign the values of the variable i and the object str in one statement, we can call the two-argument constructor. By calling a constructor inside another constructor we use the keyword this as follows.
    The correct answer is: this(“x”, 1); See the code below!
public class MyClass
{
  String str;
  int i;
  
  MyClass()
  {
    this("x", 1);
    i += 2;
    str += "x";
  }
  MyClass(String str, int i)
  {
    this.i = i;
    this.str = str;
  }
  public static void main(String[] args)
  {
    MyClass mc = new MyClass();
    System.out.print(mc.str + mc.i);
  }
}





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 *