I am really confuse why in this small example i is still 0:
public static void main(String[] args) {
int i = 0;
inc(i);
System.out.println(i);
}
private static void inc(int i) {
i++;
}
probably very easy question but I dont see it
Java passes parameters by value.
So the i in the method inc is really just a copy of the "original" i in the main method. You increment that copy, but that has no influence on the original variable i outside.
See this question for a more detailed explanation.
This is because you're using a primitive integer, essentially you're passing the value of i to inc not a reference to i. In this case just return a value from your inc method:
public static void main(String[] args) {
inc i = 0;
i = inc(i);
System.out.println(i);
}
private static int inc(int i) {
return i++;
}
Of course, if you're passing around objects then you are passing by reference and so you will be able to mutate without returning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With