0

I'm learning the Java language and am trying to do this:

public class IntegerPlusOne {
    public static int addOne(int n) {
        n = n + 1;
        return n;
    }
    public static void main(String[] args) {
        int n = 0;
        addOne(n);
        System.out.println(n);
    }
}

It should be printing "1", but instead it print zero. No matter what I set n equal to, the addOne function never changes it and I think the function is broke, but if I test it on its own it returns one more than whatever int I send to it which really confuses me.

1 Answers1

0

In java, a function cannot change the value of a parameter passed into it as they are passed by value. You can try to print the value returned from the addOne (n) function:

public class IntegerPlusOne {
    public static int addOne(int n) {
        return n + 1;
    }
    public static void main(String[] args) {
        System.out.println(addOne(0));
    }
}
Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29