Search code examples
javafor-loopjava-11multiple-conditions

multiple conditions Under the 'for' loop


Why doesn't the conditional Boolean in the standard for loop below behave as expected? I'm trying to get 3 and 4, indexes 2 and 3 in the array below to print out. If I try to specify the range in the condition of the for loop it doesn't run the loop. To test the conditional in an if condition ( see 2nd listing it works )

Why doesn't it simply work just in the for loop ?

int[]weather = {1,2,3,4,5,6,7};
for(int i=0;i>1&&i<4; i++ ) {
    //if(i>1&&i<4) {
        System.out.println("Weather is ===> "+weather[i]);
    //}
}

nothing printed...

int[]weather = {1,2,3,4,5,6,7};
for(int i=0;i<10; i++ ) {
    if(i>1&&i<4) {
        System.out.println("Weather is ===> "+weather[i]);
    }
}

Weather is ===> 3
Weather is ===> 4

Solution

  • for(int i=0;i>1&&i<4; i++ ) {
                ^------^ expression
    

    For loops execute until the expression is false, and then stop executing. This expression is immediately false (because 0>1 is false), so it immediately stops executing. It doesn't "wait and see" if the expression becomes true again.

    If you only want the loop to execute for i>1&&i<4:

    for(int i = 2; i<4; i++ ) {