0

What is the code will print out? And why?

public class test { int x = 0; test() { x = 3; System.out.println(x); } test (int y) { x = y+2; System.out.println(x); } void doSomething(int y) { x += y; System.out.println(x); } void doMore(int y) { System.out.println(x); doSomething(y+1); } } public class mainProgram { public static void main(String[] args) { test obj1 = new test(); obj1.doSomething(1111); obj1.doMore(1111); test obj2 = new test(1111); } }

24th Mar 2019, 7:10 AM
Joseph Jostar
Joseph Jostar - avatar
6 ответов
+ 4
test default constructor gets called for initialization of object. 3 is assigned to and x is printed. 3 doSomething is called with argument 1111. 1111 is added to x and assigned to x. x is printed. 1114 doMore is called with argument 1111, prints x and calls doSomething with argument 1112. 1114 doSomething is called with argument 1112, and 1112 is added to x and assigned to x. x is printed. 2226 test constructor with arguments is called during initialization of obj2 with argument 1111. 2 is added to 1111 and assigned to x. x is printed. 1113
24th Mar 2019, 7:59 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
... If you can remove the spaces in between lines, that would be great.
24th Mar 2019, 7:29 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Joseph Jostar When you do test obj1 = new test(); You are calling the default constructor (defined on line 3) which only assigns 3 to x. When you do test obj2 = new test(1111); the program will call the constructor defined on line 7 to add 1111 to 3 and assign the result to x. You are correct for the part about doSomething.
24th Mar 2019, 8:18 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Hatsy Rei thank you i still have a few questions. 1. why test obj1 = new test(); did not print out 1113? 2. when doSomething(y+1) called it’s x= 1114? So, it’s like x=1114+1111+1 Thank you
24th Mar 2019, 8:15 AM
Joseph Jostar
Joseph Jostar - avatar
+ 1
Hatsy Rei thank you for your help and wish you have a great weekend :)
24th Mar 2019, 8:28 AM
Joseph Jostar
Joseph Jostar - avatar
0
Hatsy Rei i will
24th Mar 2019, 7:45 AM
Joseph Jostar
Joseph Jostar - avatar