+ 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; }
2 odpowiedzi
+ 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
+ 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);