2

I am trying to solve this "incrementation" problem in a Java code but I can't find myself arriving at a solution:

public class Return {
   public static void main(String[] args) {
    int n = returnn(3);
    System.out.println(n);
   }

   public static int returnn(int n) {
    return n++;
   }
}

I am supposed to return 4 but it is returning 3 instead. Why is that? Also, when I type: return n+=1it works. This is confusing me. Also, what is the difference between n++ and ++n? Any clarification is greatly appreciated.

user3140507
  • 21
  • 2
  • 5
  • 1
    Please see the bottom section of [the Java tutorial](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html) on the increment operators. – rgettman May 07 '14 at 20:15
  • ++n will worj but be warned : the value of n in the function if a copy of the value in main. So return (n+1) will have same effect as the location param n in function returnn is lost once the function returns – tgkprog May 07 '14 at 20:18
  • 3
    Just `return n+1;` There is no need to increment the local variable. – clcto May 07 '14 at 20:18
  • you are using postincrement. 3 is correct. – DwB May 07 '14 at 20:18

3 Answers3

3

You have to write return ++n because return n++ evaluates to the original value of n, and ++n evaluates to the value of n after being incremented.

Pacane
  • 20,273
  • 18
  • 60
  • 97
1

Try the following;

public class Return {
    public static void main(String[] args) {
        int n = returnn(3);
        System.out.println(n);
    }

    public static int returnn(int n) {
        return ++n;
    }
}
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
madteapot
  • 2,208
  • 2
  • 19
  • 32
1

n++ increments n by 1 AFTER evaluating n's current value

++n increments n by 1 and then evaluates its value

Your method returnn(int) should return ++n, instead of n++.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
Lucas Oliveira
  • 3,357
  • 1
  • 16
  • 20