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 OR i 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?
The error is in this line:
while(i<100 & i%2==0){
& should be replaced with &&:
while(i<100 && i%2==0){
U have tearn the logical operators...
and it is a logical operator it can be true only if 2 operators are true( x>5 and y<7) will be true if only x>5 is true and y<7 is true that is give us the condition is true but if one of them is not verified the condition is false....
but if we have or operator the condition will be true only if one of them is true or both........
so let's explain ur code.
You have condition (i<100 and i%2==0).
0%2 ==0 so it is true and of course i<100 so while returns true(both true at the same time) but when i==1 here we have a problem 1%2!=0 so i<100 is true but i%2==0 is false so we get **true && false ** the result is false .
(true && true==true) (false && true==false) (false and false==false) (true ||true==true) (true || false==true) (false||false==false)
Related
First of all I know what is difference between = and ==. I want to use = to implicitly make infinite loop.
So my code looks like this:
boolean flag= true;
while (flag=false){
System.out.println("inside loop");
}
System.out.println("rest");
Unfortunately it doesn't enter the loop and prints "rest". Why? Am I reading this wrong?
In while condition I am assigning value false to flag. So it loops while flag=false (which is).
And when I do this(changed from false to true) it enters infinite loop:
boolean flag= true;
while (flag=true){
System.out.println("inside loop");
}
System.out.println("rest");
In my opinion both of these examples should enter the loop. But only the 1st one does. Please help me understand this. Thanks
This is due to the way assignment operators works.
In your loop condition you are stating
flag = true
Which returns true, but before that is assigns true to flag
This is because we are allowed do multiple assignments at once like this:
boolean test = flag = true;
// test == true
essentially (flag = true) translates to:
assign true to flag
return true for further use
while (flag=false) does two things:
It assigns false to flag
It evaluates to while(false)
Since it evaluates to while(false), its body will not be executed.
Similarly,
while (flag=true) does two things:
It assigns true to flag
It evaluates to while(true)
Since it evaluates to while(true), its body will be executed infinitely.
The first step your while loop test does is
flag=false
immediately followed by testing its value, which is false.
On a false value, the while loop isn't entered.
The only difference between = and == is :
= is an assignment operator, you give the value to the int, boolean, or whatever is the constant / variable.
== is an operator, which is used mainly in loops (for, else for, if, and while)
For your case, I might say that you need to use == inside the while loop :
boolean flag=true;
while (flag==false){
System.out.println("inside loop");
}
System.out.println("rest");
It is also not great to use an infinite loop. You won't go outside and it will bug your code.
This question already has answers here:
Using NOT operator in IF conditions
(8 answers)
Closed 7 years ago.
I have a boolean variable collision initialized to false.
Now in an if statement, suppose my if condition is the following:
if(!collision)
does this mean that the if statement will execute if collision is the opposite of what is initialized? Meaning, will it execute when !collision returns true?
Just a bit confused since I initialized it to false, and I want this if statement to run when collision is false, but don't know if !collision is the right way to do it or not.
Code as requested. Still confused on what the condition would be. I have collision initialized to false. As a result, I want the statement to be executed when it is false. Should I write if(collision) or if(!collision)?
boolean collision = false;
boolean winner = false;
while(!winner){
//Main loop where user will be able to move the ships and try to destroy the ship
//boolean shipAlive = true/false; YET TO ADD!
//if(!shipAlive) -> winner = true; YET TO ADD!
//movement of ships
if(!collision){
System.out.println("Player 1: L, R, or S? (L = Left, R = Right, S = Stay)");
String p1Input = IO.readString();
int k = movement(p1Input, player1);
while (k == 1){
System.out.print("Error! Enter either L, R or S: ");
p1Input = IO.readString();
k = movement(p1Input, player1);
}
}
collision = fireProjectileUp();
if(collision){
winner = true;
}
Yes, it is the right way to do it:
In if (!someBoolExpr) { ... }, the "then-clause" will run if someBoolExpr == false.
See the JLS ยง15.15.6: Logical Complement Operator ! for more information:
The value of the unary logical complement expression is true if the (possibly converted) operand value is false, and false if the (possibly converted) operand value is true.
! represents NOT in Java. So if you have something like
if(!true) {
//doSomething
} else {
//Something else --- This is executed.
}
if(!false) {
//doSomething --- This is executed.
} else {
//Something else
}
true and false are the final result of your comparison operations
! means not, so your expression will be translated to if(NOcollision).
Check documentation for further info.
Yes, your if statement will be executed when collision is false.
!false returns true
You've asked a question, but I suspect this is a bit of an XY problem for you. You've asked about clarification of the ! operator, then proceeded to explain exactly what a not operation is.
When constructing your conditions, you want to manipulate the logic so that it evaluates to true when you want it too. For example, I want something to run if there has been a collision.
if(collision)
Simple. This is because this will evaluate to true when you want it too. Now you want something to run if their hasn't been a collision.
if(!collision)
Once again, it evaluates to true if collision is false. Or, when you want it too. The trick here is working out how to express what you want in a way that the compiler understands, and this is done through logical expressions that resolve to some boolean true or boolean false.
EDIT
Just incase, ! operator is simply the opposite of the value. !true is false, !false is true. Going by what I explained above, you can combine this knowledge to create your solution.
When if(!collision) is executed then first of all it checks the value of collision. Let's assume its is 'false'. Then ! operator converts it to true. opposite of false. Then the value is 'true ' so, if statement will execute its code block.
Code:
public static char f( char c ){
System.out.print( c++ );
return c--;
}
public static void main(String[] args)
{
if( f('j') == 'k' || f('f') == 'f'){
System.out.println( f('d') );
}
}
Can someone please explain to me why this prints "jde"??
Intuitively, I thought it would print "kged".
The value of the expression c++ is the value of c BEFORE it gets incremented. And the value of the expression c-- is the value BEFORE it gets decremented.
So in the first call to f in your example, c starts off as 'j'. Then the line System.out.println(c++); prints 'j' and increments c, so that it's now k. On the next line, it returns the new value of c, which is 'k'.
Since the first half of the if condition is true, the second half is not evaluated. We jump straight into the body of the if. But this works the same way as before - it prints 'd' and returns 'e'. The 'e' is then printed.
c++ is incremented after the System.out.print, so it prints 'j' first.
The second part of the if statement is not evaluated since f('j') returns 'k' as the decrement is applied after the return.
Then d is printed because f('d')' is called which first prints 'd' and then the result of the function 'e'.
If you want to understand why a problem is doing something, especially if it is rather unexpected, it is a good idea to get familiar with a debugger. With that you can step through every instruction, and see the state of your program at every execution step.
As an exercise, write a program which is using those functions, but prints qed (quod erat demonstrandum).
In the if condition is f('j')=='k' which is true and that is why other condition is not being checked. Here f('j') methods prints j and returns 'k' and after returning c is again 'j'. Now in System.out.println(f('d')); f('d') prints d and returns e which is printing in main method. So the output is jde
Ok, i am building program to check many fields. If at least 1 field is not ok then i don't want my program to spend time to check other fields. So let look at this code:
// Util.isReadyToUse method return true if the string is ready for using, & return false if it is not.
boolean isOK=true;
if(!Util.isReadyToUse(firstName)){
isOK=false;
}
else if(isOK && !Util.isReadyToUse(lastName)){
isOK=false;
}
else if(isOK && !Util.isReadyToUse(email)){
isOK=false;
}
.....more checking
if(isOK) {
//do sthing
}
Ok, when running, the program will first check !Util.isReadyToUse(firstName). Suppose it returns (isOK=false). Next the program will check isOK && !Util.isReadyToUse(lastName).
So my question here is that Since the isOK currently false, then will the program spend time to check the condition !Util.isReadyToUse(lastName) after &&?
Ok, As a human being, if you see isOK=false and now you see isOK && !Util.isReadyToUse(email), then you don't want to waste time to look at !Util.isReadyToUse(email) since isOK=false and u saw && after isOK.
Will machine also work like that?
I am thinking to use break but why people say break doesn't work in if statement:
if(!Util.isReadyToUse(firstName)){
isOK=false;
break;
}
else if(isOK && !Util.isReadyToUse(lastName)){
isOK=false;
break;
}......
What is the best solution in this situation?
So my question here is that Since the isOK currently false, then will
the program spend time to check the condition
!Util.isReadyToUse(lastName) after &&?
Java is smart, if you have a condition if(somethingFlase && something), then something won't be reached due to Short-circuit evaluation. Since the whole expression will be false regardless of the second condition, there is no need for Java to evaluate that.
From 15.23. Conditional-And Operator &&:
If the resulting value is false, the value of the conditional-and
expression is false and the right-hand operand expression is not
evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated.
if(a && b) - if a is false, b won't be checked.
if(a && b) - if a is true, b will be checked, because if it's false, the expression will be false.
if(a || b) - if a is true, b won't be checked, because this is true anyway.
if(a || b) - if a is false, b will be checked, because if b is true then it'll be true.
No, it shortcuts the rest of the predicate.
That's you'll see things like
if(A != null && A.SomeVal == someOtherVal)
Java supports what is referred to as Short-Circuit Evaluation. See this page:
http://en.wikipedia.org/wiki/Short-circuit_evaluation
What this means is that if the first boolean in your statement is enough to satisfy the statement, then the rest of the values are skipped. If we have the following:
boolean a = false;
boolean b = true;
if(a && b) /*Do something*/;
'b' will never be checked, because the false value for 'a' was enough to break out of the if statement.
That being said, your program will never take advantage of this because the only time isOK is set to false is within one of your else if statements.
As the other responders mentioned Java will do the smart thing.
But it could be the case that you want Java to continue to check, in that case you can use & vs && or | vs ||.
if (someMethod() | anotherMethod() {
If the first method reutrns true, Java will still execute the second method.
if (someMethod() & anotherMethod() {
If the first method is false, Java will still execute the second method.
No, Java won't "waste time" for it. It's called short circuit evaluation.
This mechanism is commonly used e.g. for null checking :
if (foo != null && foo.neverFailsWithNPE()) {
// ...
}
You don't need to use break on an if..else if.. else statement because once it finds a condition which is true the rest aren't even looked at.
could someone explain why this code output is
not equals
not equals 2
in the first if statement it seems that a = 0 b/c is a postfix increment; therefore a will not increase untile next line; however, the two a's are not equal why? and in the second if when I run the debugger the value of a is 2, but the test is false, why?
public static void main (String[] args)
{
int a = 0;
if (a++ == a++) {
System.out.println("equals");
} else {
System.out.println("not equals");
}
if (++a == 2) {
System.out.println("equals 2");
} else {
System.out.println("not equals 2");
}
}
it's not that it waits until the next line. The == is a 'logical' operator so the expression on each side is evaluated first, each of which has the side-effect of incrementing the 'a' value. The result of the 1st increment is used on LHS, result of 2nd on RHS.
In these cases it matters not whether the operator is 'prefix' or 'postfix'
a++(post increment) would increment a first and then assign it to the variable. in your first case
(a++==a++) in the first post increment a value would be incremented by 1 first but not assigned yet, but when it reaches the second a++, now the a value is assigned and you are incrementing it again.
for example
if say a=0;
(a++==a++) would be (0==1)
so now the a value would be 2 after evaluating the if.
for your second case
(++a==2) here a would be incremented to 3 , (3==2) which is false thus the else if executed
EDIT: just realized you asked also for first not equals, this just answers the second one yet.
Because
a is already 2 (already incremented twice)
++a is 3 so
3 == 2 is false since prefix is applied before evaluation.