Java for Loop evaluation

前端 未结 9 2304
孤独总比滥情好
孤独总比滥情好 2020-12-03 21:45

I want to know if the condition evaluation is executed in for and while loops in Java every time the loop cycle finishes.

Example:

9条回答
  •  旧巷少年郎
    2020-12-03 22:14

    Yes, the expression must be evaluated for each iteration of the loop to determine whether to stay inside the loop or continue program execution.

    Remember, you can do things like this:

    for(int a = 0, z = 26; a < z; a++, z--){
        // Do some work
    }
    

    In that case, both sides of the expression will change and must be evaluated for each iteration.

    And you're right, if you have calculations in the for loop condition that can be moved out to a separate variable, you should do that:

    for(int i = 0; i < ((someCount / 2) * 21.6); i++){
    }
    

    Could easily be:

    int maxVal = (someCount / 2) * 21.6;
    
    for(int i=0; i < maxVal; i++){
    {
    

提交回复
热议问题