I have a little doubt here,i have a code as
int num=0;
for(int i=0;i<5;i++){
num=num++;
System.out.print(num);
}
why is the output always 00000
I have a little doubt here,i have a code as
int num=0;
for(int i=0;i<5;i++){
num=num++;
System.out.print(num);
}
why is the output always 00000
The ++ operator increments num last, so when num is 0, you are setting it to 0 again.
It has to deal with how the ++ operator increments num, and what num is truly pointing to. To avoid it, just use num++
Interestingly enough, num=++num will correctly increment and assign the incremented value, though the whole purpose of the ++ operator, either pre or post, is that it modifies the value directly. You do not have to re-assign it back to the value.
use num++;
int num=0;
for(int i=0;i<5;i++){
num++;
System.out.print(num);
}
Output 12345
num=num++;
is equals to num=num;
num=++num;
is equals to num=num+1;
num=num++;
is equal -
num = num;
num ++;
First it assign then it try to increment the num which is already assigned. For better calrification -
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 generated byte code would 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
...
num=num++;
Here you are using postfix ++ operator with assignment.So that means you assigned the value first and then incremented it.
So
num = num++;
equivalent to
num = num;//line1
num+1;//line2
Deep look at line2 .The result of num+1
is not assigned to anything.So num
is always have the value assigned at line1.i.e.,0 in your case.
Ok, In java =
operator works as follows
L.H.S=R.H.S
right hand side value will assign to left hand side variable.
In here initial value of num=0
and
num=num++
this increment not influence in place to num
. if you do ++num
it will effect at once in palace. so again you are assign 0
for num
. So entire process this will happen continuously until loop stop.
for explanation,
Post Increment(n++) : First execute the statement and then increase the value by one.
here, value of 'num++' is assigned to num and that is before increment and is 0. so num will have always value 0.
you can use simply num++ there.