+ 1

Why output is not 16?

I am using parameter passing. but I use return type for the program. but the output is not return value, it shows assigned value. y ? public class Program { public static void main(String[] args) { int x=4; square(x); System.out.println(x); } static int square(int x){ x=x*x; return x; } }

1st May 2017, 6:54 AM
Sankar KR
Sankar KR - avatar
2 Réponses
+ 7
You need to use x = square(x); instead of square(x); as this doesn't change the value of variable of data type int.
1st May 2017, 6:58 AM
Vishal Prajapati
+ 4
in java primitive variables are passed by value (a copy is created and changes on that copy don't affect the original variable. Objects are intead passed by referenve.
1st May 2017, 8:03 AM
seamiki
seamiki - avatar