Java for Loop evaluation

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

    index < tenBig.length will be execute before every time the loop cycle starts.

        public static void main(String[] args) {
            int[] tenBig = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
            for (int index = 0; isEvaluated() && index < tenBig.length; index++) {
                System.out.println("Value at index: " + tenBig[index]);
            }
        }
    
        public static boolean isEvaluated() {
            System.out.println("evaluated");
            return true;
        }
    

    It will print "evaluated" just before cycles starts. And one more time before loop finishes.

提交回复
热议问题