Can't we use Boolean logical operators (such as &,|,!,^ etc) in java flow controls ( for loop,while loop etc) ???
I want to print all even numbers between 1 and 100.So I used below two source codes.
import java.util.*;
class Example{
public static void main(String args[]){
int i=1;
while(i<100){
if(i%2==0)
System.out.print(i+" ");
i++;
}
}
}
This code is compiled and prints all even numbers between 1 and 100.
import java.util.*;
class Example{
public static void main(String args[]){
int i=1;
while(i<100 & i%2==0){
System.out.print(i+" ");
i++;
}
}
}
This code is compiled without any error.but doesn't give any print.
Why is that ? Can't we use Boolean logical operators within a while loop ?
Remember that the while loop condition is the condition to continue the loop, which means that when the condition is false, the loop stops.
If you negate the condition in the second code:
!(i<100 & i%2==0)
Using De Morgan's Law, This is equivalent to:
i>=100 | i%2!=0
Or in words:
i
is greater than or equal to 100 ORi
is odd.
This is the stopping condition of the while loop. Well, i
is initially 1, which is odd, so the loop stops without even executing one iteration.
In other words, you can't rewrite the first code as the second code. They are not equivalent. What goes in the if
condition goes in the if
condition. You can't "merge" it into the while
condition, because they are for different purposes.
I also recommend &&
for the logical AND, as it only evaluates the right operand when necessary. For more info, see What is the difference between & and && in Java?