Java puzzle 19: Overloading methods

  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 null3 to the standard output. Write only one statement at line 9. As a result of that statement the output of the program becomes x5.
What is that statement?

Java puzzle 19: Overloading methods

Level: Normal

public class MyClass
{
  String s;
  int i;
  
  public void meth()
  {
    i += 3;
    // add your statement here!
    System.out.print(s + i);
  }
  public void meth(String s, int i)
  {
    this.s = s;
    this.i += i;
  }
  public static void main(String[] args)
  {
    MyClass mc = new MyClass();
    mc.meth();
  }
}

Author: Sar Maroof

Answer explanation

  1. To solve this puzzle we need to reassign the instance variables str and i.
  2. To do that with only one statement we need to use the method myMethod with two parameters.
    if we pass the parameters x and 5, the output becomes x8, because the statement i += 3; increments the value of i by 3.
    Therefore we pass the parameters x and 2 to the method as follows.
    The correct answer is:  meth(“x”, 2);





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 *