+ 1

the answer is 16 but he does not leave fill 16.

the answer is 16 but he does not leave fill 16.

19th Aug 2016, 5:00 PM
Marcelo Cordeiro Basílio
Marcelo Cordeiro Basílio - avatar
3 ответов
+ 8
answer is 4, because the result of square(x) is not assigned to x again. When you pass x to square() as a parameter, you are passing the method a value, and not the variable itself, so it won't change. if it was an object, then you would be passing a reference to the object, instead of the value, and the object would be modified.
19th Aug 2016, 8:36 PM
Roberto Notario
Roberto Notario - avatar
+ 1
// This is the way you think is working, but is not. public class MyClass { static void addOneTo(int num) { num = num + 1; System.out.println(num); } public static void main(String[ ] args) { int x = 5; addOneTo(x); // System.out.println(x); } }
29th Aug 2016, 12:17 PM
Edson Palencia Vanegas
Edson Palencia Vanegas - avatar
0
It's because the value of 16 isn't being passed back to the main method as it's a void method with no return value. I really recommend this site (http://www.pythontutor.com/visualize.html#mode=edit) which goes through your program step by step to show you what is being executed and when. Try the code for this example, make sure you select Java8 from the drop down menu. public class MyClass { static void square(int x) { x = x*x; } public static void main(String[ ] args) { int x = 4; square(x); System.out.println(x); } } Note: Due to the sloppy way programs work on SoloLearn you cant copy and paste many into the editor as they wont work. It's also annoying that they place the main method before the rest of the code when convention dictates the main should come last.
14th Feb 2017, 11:15 AM
Barking_Mad