Reputation: 855
I would need explanation, why is if()
block inside of while()
statement executed.It's said that: The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. So please, take a look at this code:
class test{
static int x;
public static void main(String args[]){
while(x!=5){
x=x+1;
if(x==5)
System.out.println("I'm 5 now!");
}
}
}
Once variable x gains amout of 5, shouldn't be (x!=5)
considered as false? So how can be if block executed? Basically it seems like it returns true boolean value for expression 5!=5.
Thank you for explanation!
Upvotes: 1
Views: 190
Reputation: 18861
When you enter the loop's body and x == 4
, it proceeds.
Then, you add 1
to the variable.
It's 5
now, so the if
's condition is true!
Upvotes: 3
Reputation: 579
It enters the while loop while x=4 i.e, (4!=5 right??)
and x=x+1 is executed inside the while loop, so x=5; and the next line inside while loop is if(x==5) System.out.println("I'm 5 now!");
as value of x is 5 , the execution enters the if condition and we will get the output as "I'm 5 now!"
Upvotes: 2
Reputation: 35557
while(x!=5){ // here maximum value accept as true is 4
x=x+1; // now 4+1 and x =5
if(x==5) //yes condition satisfied
System.out.println("I'm 5 now!"); //so out put will print
}
Upvotes: 2
Reputation: 20618
The expression x == 5
is evaluated to true, because x is changed inside the while loop.
When x equals 4 (which means x != 5
still evaluates to true), the next line (x = x + 1
) results in x being 5.
Upvotes: 1
Reputation: 61510
While loops are known as pre-condition loops, meaning they check a condition before executing some block of statements.
So when x
becomes 5
in the body of the loop, the last condition that was actually checked was x != 4
.
x != 5
will be checked the next iteration of the loop.
Upvotes: 2
Reputation: 121720
When you enter the loop with X
equal to 4, it is first incremented to take value 5, therefore satisfying the expression x == 5
.
But then, at the next iteration, the condition in while
is not true anymore.
Upvotes: 2
Reputation: 4588
This is because your x
becomes equal to 5 after it enters the loop. On the next iteration the loop stops. You should move x=x+1
line after the if
to make it work the way you want
Upvotes: 3
Reputation: 8928
If x == 4 then while is satisfied x != 5
. Then you increment x x = x+1
and have x == 5
. That's why
Upvotes: 5