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
- To solve this puzzle we need to reassign the instance variables str and i.
- 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);
Suggested Articles
![]() ![]() ![]() |