0

I have a question about Java being pass-by-value. I know that variables declared outside a method will not change their values since when I call I method on the variables, the method will only be using the value assigned to them. But in this case, I do not understand why int result does not get a value of 2. As increment() will get the value of x, so 1 and increment it by 1 and store the value in the result variable.

public class Increment {
      public static void main(String[] args) {
        int x = 1;
        System.out.println("Before the call, x is " + x);
        int result = increment(x);
        System.out.println("After the call, x is " + result);
      }
      public static int increment(int n) {
       return n++;

      }
    }
yy123q
  • 7
  • 1

1 Answers1

1

Post increment operator n++ increments the value of n by 1, but returns the previous value. Therefore increment(x) returns x, not x+1.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Then, how i++ is useful in a for loop? – yy123q Oct 26 '18 at 07:00
  • @yy123q in a for loop you don't assign the value returned by `i++` to a variable. You just check the value of `i` after the `i++` call, which gives you the incremented value. – Eran Oct 26 '18 at 07:01