Here the output is 0, but why not 1 ? is the scope of variable 'a' ends with the method ..? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Here the output is 0, but why not 1 ? is the scope of variable 'a' ends with the method ..?

public class Program { public static void main(String[] args) { int n = 0; increment (n); System.out.println(n); } static void increment(int a) { ++a; } }

14th Dec 2018, 4:43 AM
Sharief
Sharief - avatar
2 Answers
+ 3
That's correct Sharief. You are passing the variable n by value, which means that you are only changing the value of n (zero) and not the variable itself.
14th Dec 2018, 5:01 AM
Zeke Williams
Zeke Williams - avatar
+ 2
If you want the value of <n> changes you can modify the "increment" method to return int instead of void, and have <n> to capture the return value (an incremented value of <n> itself); static int increment(int a) { return ++a; } In main method ... int n = 0; n = increment(n);
14th Dec 2018, 6:49 AM
Ipang