Java for Loop evaluation

前端 未结 9 2277
孤独总比滥情好
孤独总比滥情好 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++;
    }
    
    0 讨论(0)
  • 2020-12-03 22:28

    Short Answer: the condition is evaluated every time so:

    WRONG:

    for (int i = 0; i < Math.random() * 50; i++) {
        System.out.println("" + i);
    }
    

    CORRECT:

    double random = Math.random();
    for (int i = 0; i < random * 50; i++) {
        System.out.println("" + i);
    }
    
    0 讨论(0)
  • 2020-12-03 22:29

    Do you ask wether the compiler caches the tenBig.length value since he knows it won't change during the loop? Or you ask wether the compiler automatically knows that the whole expression index < tenBig.length does not need to be evaluated for the next 9 times?

    0 讨论(0)
提交回复
热议问题