Why in for loop value assigned to a temp variable not print as it is?

Abhishek :

My Demo Program :

public static void main(String x[])
{
    int tempVal = 5;
    for(int i = 0; i < 5; tempVal = i++)
    {
        System.out.println("Value Of i: "+i +" _tempVal:"+tempVal);
    }
}

Output :

Value Of i: 0 _tempVal:5

Value Of i: 1 _tempVal:0

Value Of i: 2 _tempVal:1

Value Of i: 3 _tempVal:2

Value Of i: 4 _tempVal:3

Why variable "tempVal" is not having same value as 'i' ?

Sebastian I. :

Because you're post-incrementing. That means that tempValue = i but then i gets incremented.

And why at the first iteration tempValue is still 5 ? There is a nice figure in OCA Programmer Guide

enter image description here

which explains every step during a for loop and what is essential here is that the update statement is executed AFTER body execution.

To be more specific, the figure is from "Chapter 2 (Operators and statements)" (Figure 2.7)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=193585&siteId=1