Example java loop with operator increment

I have a little doubt here, I have code like

int num=0; for(int i=0;i<5;i++){ num=num++; System.out.print(num); } 

why the output is always 00000

+4
source share
7 answers

use num ++;

 int num=0; for(int i=0;i<5;i++){ num++; System.out.print(num); } 

Exit 12345

Num = Num ++;

equal to num = num;

Num = Num ++;

equal to num = num + 1;

+3
source

The ++ operator increments num, so when num is 0, you set it to 0 again.

It must deal with how the ++ operator increments num, and what number really indicates. To avoid this, just use num ++

Interestingly, num = ++ num will correctly increment and assign an extra value, although the whole purpose of the ++ operator, both pre and post, is that it directly changes the value. You do not need to reassign it to a value.

+9
source
 num=num++; 

equal to -

 num = num; num ++; 

First he appoints, then he tries to increase the number that is already assigned. For better framing -

  0 iconst_0 1 istore_1 [num] 2 iconst_0 3 istore_2 [i] 4 goto 22 7 iload_1 [num] // Load first 8 iinc 1 1 [num] // incement but no reload 11 istore_1 [num] // store old load value 12 getstatic java.lang.System.out : java.io.PrintStream [16] 15 iload_1 [num] 16 invokevirtual java.io.PrintStream.print(int) : void [22] 19 iinc 2 1 [i] 22 iload_2 [i] 23 iconst_5 24 if_icmplt 7 27 return 

if we consider num=++num;

then the byte code generated will be -

  0 iconst_0 1 istore_1 [num] 2 iconst_0 3 istore_2 [i] 4 goto 22 7 iinc 1 1 [num] // Increment 10 iload_1 [num] // load the incremented value 11 istore_1 [num] // store the loaded incremented value ... 
+2
source

What postfix ++ does .

You can use:

 num++; System.out.print(num); 
+1
source

num=num++;
Here you are using the postfix ++ statement with the assignment. This means that you first assigned a value and then increased it.
So,

  num = num++; 

equivalently

  num = num;//line1 num+1;//line2 

A deep look at line 2. The result num+1 not assigned to anything. So num always has the value assigned in line1.ie, 0 in your case.

+1
source

Ok, the java = operator works as follows

LHS=RHS value of the right hand is assigned to the left side of the variable.

Here the initial value is num=0 and

num=num++ this increment does not affect num . if you do ++num , it will be spectacular immediately in the palace. so again you assign 0 to num . Thus, the whole process will occur continuously until the cycle stops.

+1
source

to explain

Post Increment (n ++): First, execute the statement, and then increase the value by one.

here the value of 'num ++' is assigned to num, and this is 0. before the increment. Therefore, num will always be 0.

you can just use num ++ there.

+1
source

Source: https://habr.com/ru/post/1498306/


All Articles