Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i and i=i++ in for loop java [duplicate]

Tags:

java

for-loop

What is the logic behind this behaviour?

 int i=0;
    for(int k=0;k<10;k++){
    i++;
    }
    System.out.println("i="+i);

Output=10; //Exepcted



 int i=0;
    for(int k=0;k<10;k++){
    i=i++;
    }
    System.out.println("i="+i);

Output=0; //Surprised :) 

Can anybody throw some light on above functionality?

like image 754
vivek shetty Avatar asked May 02 '13 10:05

vivek shetty


People also ask

What is ++ i and i ++ in Java?

Increment in java is performed in two ways, 1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1. 2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.

What is i ++ and ++ i in for loop?

Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.

What is the difference between ++ i and ++ i?

The only difference is the order of operations between the increment of the variable and the value the operator returns. So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.

What is the difference between I -- and -- I in Java?

There is no difference in your case. --i is pre-decrement and i-- is post-decrement.


1 Answers

See this brilliant answer:

x = x++;

is equivalent to

int tmp = x;
x++;
x = tmp;

From this question.

like image 144
Maroun Avatar answered Nov 03 '22 23:11

Maroun