+ 1

Why not 16

Why not 16 and why 4: The code is: (java) public static void main(String[ ] args) { int x = 4; square(x); System.out.println(x); } static void square(int x) { x = x*x; }

6th Sep 2020, 5:56 PM
Muhammad Sultan Al Mahfuz
Muhammad Sultan Al Mahfuz - avatar
2 Réponses
+ 5
cause you are not changing the value of x. x is not a ref type It's a value type .Try this if you want to make the value of x 16: https://code.sololearn.com/cg5r01FtqI4j/?ref=app
6th Sep 2020, 6:12 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 3
Java is a pass by value. When you pass x(3) The square method will create a new int named x and it's assigned to the passed value which is main's x(3). The square's x and main's x do not hold the same address. So when you manipulate square's x it does not affect the main's x. The solution you're looking for is to change square's void into int, use "return x*x;" in the square method, and assign it in main, e.g. x = square(x);
6th Sep 2020, 6:05 PM
Odyel
Odyel - avatar