-2

i have tried this ,found the questions

public class Baz {
    public static void main(String[] args) {
        int num = 5;
        for(int i=0 ;i < 4 ; i++) {
          num = num++;
        }
       System.out.println("Value is :" + num);
    }
}

the result print Values is 5, What happen ?

FAMMMM
  • 69
  • 1
  • 1
  • 7

4 Answers4

2
num = num++;

is the same as

num = num;

because the numerical value of the expression num++ is the value of num before it is incremented; so although num++ has the side-effect of incrementing num, it is immediately reverted by the assignment,

As such, the value of num is left unchanged.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
2
num = num++;   // don't do this

num++ increments the variable, but it first evaluates to the current value, which is then assigned to the variable by num =. The incremented value is just discarded.

In other languages (such as C), this is even undefined behaviour.

Thilo
  • 257,207
  • 101
  • 511
  • 656
0

num++ is the same as num = num +1

So you should just do as follows:

public class Baz {
    public static void main(String[] args) {
        int num = 5;
    for(int i=0 ;i < 4 ; i++) {
       num++;
    }
   System.out.println("Value is :" + num);
}

}

SCouto
  • 7,808
  • 5
  • 32
  • 49
  • 2
    No: `num = num++` is the same as `num = num`. – Andy Turner Jun 02 '16 at 09:19
  • Yes, and num++ is the same as num = num +1, that's what I said – SCouto Jun 02 '16 at 09:20
  • No: the value assigned to by this expression is the value of `num` before it is incremented, *not* after. That is the difference between post- and pre-incrementing. – Andy Turner Jun 02 '16 at 09:23
  • `num++` is not the same as `num = num + 1`. If one changes the code to `num = ( num = num + 1 )` it does not stay at 5. – Thilo Jun 02 '16 at 09:23
  • Right, that's why i said to modify the line as in the answer, which is the same as : for(int i=0 ;i < 4 ; i++) { num = num +1; } – SCouto Jun 02 '16 at 09:27
0

The line num = num++ makes no sense. num++ is equal to num = num + 1

So you have to change your code into:

public class Baz {
    public static void main(String[] args) {
        int num = 5;
        for(int i=0 ;i < 4 ; i++) {
          num++;
        }
       System.out.println("Value is :" + num);
    }
}
CloudPotato
  • 1,255
  • 1
  • 17
  • 32