Java for Loop evaluation

前端 未结 9 2333
孤独总比滥情好
孤独总比滥情好 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:26

    Yes. Specifically, the condition part is executed before each loop body. So it's entirely possible that you never enter the body of the loop at all.

    So taking your example:

    for(int index = 0;index < tenBig.lenght;index++) {
        /* ...body... */
    }
    

    This is the logical (not literal) equivalent:

    int index = 0;
    while (index < tenBig.length) { // happens on each loop
        /* ...body... */
    
        index++;
    }
    

提交回复
热议问题