Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot increment integer in void method

Tags:

java

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

like image 505
hudi Avatar asked May 14 '26 19:05

hudi


2 Answers

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.

like image 78
Joachim Sauer Avatar answered May 16 '26 10:05

Joachim Sauer


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!