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.
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:
Difference between "!= true" and "== false"?
(2 answers)
Closed 4 years ago.
I've faced a situation where "!= true" gave me a different output than "= false". I thought that if something isn't true it'd be false automatically. Can anyone please explain me how it works? Thanks!
It gives different output because you confused with Comparison vs Assignment
!= will compares the value with RHS and =false do an assignment to LHS. If you wish to check for equality use the == operator instead.
And I don't think it won't make much difference when you compare in difference styles since both do the same job unless you have some weird line of code.
== is comparison operator, = is assignment operator
!= is not equal to, and == is equal to
In addition to the other answers,
if something isn't true it'd be false automatically
is also wrong.
(Boolean) null != true is true, but (Boolean) null == false is of course false.
!= true is used a comparator. It compare the LHS to true. However = false is an assignment. An equivalent of != true will be == false. == is also a comparator operator that checks for equality while != checks for inequality.
It is all about writing or checking the value...
look this example...
boolean flag = true; a boolean variable is defined and assig to true
if (flag!=true) { //you should do instead if(!flag)
//this is checking the content of the flag variable
}
if (flag=true) { //you should do instad if(flag)
//this is writing the content of the flag assigning it to true
}
In a boolean statement, if you use != true, if the boolean is null, the operator will allow it to run whatever it is comparing. If you use == false, it will only run if the boolean is currently set to false.
First is comparison, in later case you are assigning
I have a code like this.
public void test()
{
final boolean passDay = true;
final int status;
//if the right side takes place means i need status value below and is set
//if only the left side is takes place i dont care about status because i will not use it
if(!passDay && ((status=loadStatusValue()))== Constants.YORK_CORK_EMPTY_SET)
System.out.println("inside 1");//I DONT CARE ABOUT STATUS VALUE
else
{
if(passDay)System.out.println("BAMBA");//I DONT CARE ABOUT STATUS VALUE
else
{
//HERE STATUS ALWAYS WILL HOLD A VALUE SIMPLYBECAUSE RIGHT SIDE
//IS ALREADY EVALUATED BECAUSE passDay=false and !passDay=true
System.out.println(status);
//I MEAN I USE STATUS ONLY AFTER BEING INITIALIZED
//WHY variable status might not have been initialized IS SHOW IF I AM HERE IS BECAUSE STATUS HAS A VALUE.
}
}
}
private boolean compute(){return true;}
private int loadStatusValue(){return Constants.BOTH_YORK_CORK_SET;}
What i think in this method everything works i use the status int variable when was already set even is not defined in the initialization.
As you can see the passDay is a boolean means only could hold true or false i have try hardcoded with true and false and not compilation error is show when shows a compilation error when instead being hardcode i do something like it.
final boolean passDay = compute();
in fact compute is also returning a boolean could be true or false but in this case a compilation error is show variable status might not have been initialized but can't java realize that even when true status is just not used and when false the status variable is initialized or set it and used later or i am wrong?
Please read about short circuit evaluation in Java -
(condition1 && condition2).
The condition preceding the && operator if evaluates to false; the execution does not evaluate the other condition as it is not required. Regardless of the output of condition2 - false && condition2 shall evaluate to false. Try rearranging the order of conditions or initialize the variable first.
hope this helps.
&& is a short-circuiting operator. This means that in the following expression:
!passDay && ((status=loadStatusValue()))== Constants.YORK_CORK_EMPTY_SET
The right-hand operand (((status=loadStatusValue()))== Constants.YORK_CORK_EMPTY_SET) is only evaluated if !passDay is true. This means that the assignment of status will only take place if passDay is false.
If you use final boolean passDay = compute();, there is no way of knowing at compile time if compute() will return true or false.
I suspect (without having tried it) that your code will compile with compute() if you use the non-short-circuiting AND operator, &, which will evaluate the right-hand operand even if the left-hand operand is false.
I think that a better approach is just to restructure your code to make this conditional more readable. Conditionals with side effects are error-prone because it is very easy to overlook the side effect when reading the code:
if (passDay) {
System.out.println("BAMBA");
} else {
status = loadStatusValue();
if (status == Constants.YORK_CORK_EMPTY_SET) {
System.out.println("inside 1");
} else {
System.out.println(status);
}
}
Within your code, you set passDay to final meaning it's value can never be changed throughout program execution. Bear this in mind whenever you're doing conditional checks, such as if(!passDay ... ) etc.
If you expect, or intend, to have the value passDay changed, then you can initialise to true at the start of execution, but don't delcare as final
Hopefully this clears some things up.
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.
I'm making a game where there is a goalie. i want him to move back and forth forever. i have an int called goalieposx (goalie position on the x axis) and i want this is go up by 1 until it hits 200, then go down by one till its back a 0 and repeat. I've tried the folllowing
//this bit isnt in the method, its outside as global varibale
boolean forward=true
//this bit is in a method which is continiouly called nonstop
if (goalieposx<200){
forward=true;
}
else if (goalieposx>200){
forward=false;
}
System.out.println(forward);
if(forward=true){
goalieposx++;
System.out.println("forward");
}
else if (forward=false){
goalieposx--;
System.out.println("backwards");
}
}
this method is called continously. It prints true until it gets to 200, then it prints false. However, it always prints forward, never backward. So conclusion is: the boolean changes as expected but the first if is always called, it seems to ignore the condition
ive also tried this
if(forward = true){
if(goalieposx==200){
forward=false;
}
else{
goalieposx++;}
}
else{
if(goalieposx==0){
forward=true;
}
else{
goalieposx--;}
System.out.println(goalieposx);
}
but this doesnt work either, it prints 1 then 2 etc upto 200 then prints 200 forever. Anyone know how i can solve this? is an if statement the wrong idea altogether?
This is why you should never do comparison for boolean types in if, while, for, whatever. You have just done the assignment in your if statement:
if(forward=true)
the above if statement will always evaluate to true. The problem with this is, this compiles successfully in Java, as syntax wise it's alright. Compiler just checks the type of expression in if evaluates to boolean or not. And it does, so it's ok with it.
You need to do the comparison:
if(forward==true)
.. but as I said, you should not do comparison for boolean types. So, simply doing this:
if(forward)
would be enough.
You also don't need those else if in both the conditions. Just an else will work fine. Well, I don't understand the use of boolean variable at all. It seems like you don't need it. You can change your code to:
if (goalieposx<200){
// forward=true;
goalieposx++;
System.out.println("forward");
}
else {
// forward=false;
goalieposx--;
System.out.println("backwards");
}
What you were previously doing is, setting a boolean variable, based on a condition, and using that boolean variable as condition to execute another if-else block. Well, whatever you are executing in the 2nd if-else block, can simply be moved in the original if-else block, without taking the help of the middle-actor boolean variable.
if(forward=true) does not do what you thing it does.
In java = is the assignment operator and == is the comparison operator. What you are doing with that statement is saying "if assign forward to true" which will set forward to true and always return true.
What you mean to say is if(forward) and if(!forward).
In fact you don't need the else if just an else as if the boolean is not true it must be false.
A better way to do it is to get it to move to the left by adding a minus number, and to the right by adding a positive number. Here's an example of doing this with a loop:
for(int i = -10; i < 100; i++) {
xPosition += i;
}
This would add -10 then -9 etc. to the position.
In your if statements, you need to put two equal signs to check for equality.
if (forward == true){
// execute code
}
EDIT 1:
if (forward)
would be much simpler.
First let's examine what you have already written:
if (goalieposx<200){
forward=true;
}
else if (goalieposx>200){
forward=false;
}
The problem with this code being first is that it while it might set the direction to false once 'goalieposx' has reached 201, in the next call, it will set the direction back to true.
Instead, try using this clever alternative:
//This goes before the infinite loop method
counter = 0;
//Then in the infinite loop method
counter++;
if(counter > 100) {
counter = -100;
}
goalieposx = 100 + counter; //(this shifts counter from
// between -100 and 100 to 0 and 200)
The problem is you are setting the direction based on the value of the integer, instead of whether a condition has previously been met. Try this:
//this bit is in a method which is continiouly called nonstop
if (forward && (goalieposx>200)){
forward=false;
}
System.out.println(forward);
if(forward=true){
goalieposx++;
System.out.println("forward");
}
else if (forward=false){
goalieposx--;
System.out.println("backwards");
}
}