If else condition combine && and || in one row statement - java

Thank you for your time, i create some if else statement in checkbox to display result, can i combine && and || condition in one statement? for example
if (radioMale && chestPain && (leftArm || bothArm || jaw || throat)) {
highPossibilityOfHeartDisease = true;
}
User have to tick radioMale && chest pain && can tick either leftArm, bothArm, jaw or throat (one or more) to return true for highPossibilityOfHeartDisease. Is the code above valid? need some help here.

Yes you can combine && and || in a if...else statement. See it logically before considering programmatic side.
true AND true AND true AND (true OR false OR false) the condition inside brackets will be verified and set as one resulted Boolean that may be true or false according to the condition.
Then the resulting booleans will be verified linearly as normal.
You can read some articles explaining maths of boolean expressions, for example:
The Mathematics of Boolean Algebra: From StanFord University
Boolean Expressions
Boolean algebra

Related

Multiple conditions in one if statement in JAVA [duplicate]

Lets say I have this:
if(bool1 && bool2 && bool3) {
...
}
Now. Is Java smart enough to skip checking bool2 and bool3 if bool1 was evaluated to false? Does java even check them from left to right?
I'm asking this because i was "sorting" the conditions inside my if statements by the time it takes to do them (starting with the cheapest ones on the left). Now I'm not sure if this gives me any performance benefits because i don't know how Java handles this.
Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.
This means that the following code is completely safe:
if(p != null && p.getAge() > 10)
Also, a || b never evaluates b if a evaluates to true.
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use & and | it will always evaluate both sides of the expression.
Please look up the difference between & and && in Java (the same applies to | and ||).
& and | are just logical operators, while && and || are conditional logical operators, which in your example means that
if(bool1 && bool2 && bool3) {
will skip bool2 and bool3 if bool1 is false, and
if(bool1 & bool2 & bool3) {
will evaluate all conditions regardless of their values.
For example, given:
boolean foo() {
System.out.println("foo");
return true;
}
if(foo() | foo()) will print foo twice, and if(foo() || foo()) - just once.
Yes,that is called short-circuiting.
Please take a look at this wikipedia page on short-circuiting

if-else condition: AND evaluation mystery

I'm working on an app for Android. In my code I have the following lines:
if (shape != null && !created && isTap(touchDown, event)) {
DrawPrimitive newShape = listener.onTouch(event, shape);
if (newShape != shape)
canvas.onDrawingChanged(true);
}
created is a boolean member. I'm wondering because created is true but the runtime steps into my if even without calling the isTap method. If I change the ! to the false comparsion, everything works fine.
if (shape != null && created == false && isTap(touchDown, event)) {
DrawPrimitive newShape = listener.onTouch(event, shape);
if (newShape != shape)
canvas.onDrawingChanged(true);
}
So I'm wondering if the ! is not allowed. But even if so, why is my isTap method (in version one) not called and why is the inner code executed without evaluating all AND conditions.
Why isTap() isn't called: && conjunctions (and || disjunctions for that matter) are evaluated with short-circuiting from left to right: when the left hand side operand of the expression evaluates to false (true for ||), the right hand side operand does not need to be evaluated: the value of the expression is already known.
!created and created == false are the same in Java if created is boolean. If it's Boolean, you will have problems with autoboxing/unboxing:
!created autounboxes the Boolean to boolean and complements the result with !.
created == false autoboxes false boolean literal to Boolean and compares the object references. They aren't necessarily the same Boolean objects.
To avoid such problems and as a rule of thumb, don't use true or false directly in boolean expressions.
!created and created == false are equivalent. The first version should behave in exactly the same way as the second.

Does Java waste time to check conditionA in "if(isOK && conditionA)" if isOK=false?

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.

Unknown while loop usage

This page a user must choose between one of 2 checkboxes 5 times. So I wrote this:
if (box1a.isSelected() == true || box1b.isSelected() == true) {
if (box2a.isSelected() == true || box2b.isSelected() == true) {
if (box3a.isSelected() == true || box3b.isSelected() == true) {
if (box4a.isSelected() == true || box4b.isSelected() == true) {
if (box5a.isSelected() == true || box5b.isSelected() == true) {
with some other things he does when it is true.
} else {
new Error("You must select an answer at all the questions");
}
Then he only returns a error if you don't check one of the top checkboxes. Then cleary I need a while loop in there but i don't know how to uhm do it. I know how a while loop works but don't know how It would look in this situation. Please help
Also now I have to do the same with text fields and using th same methode that I got answered by you guys doesn't work. any advise?
if ((box1a.isSelected() || box1b.isSelected()) &&
(box2a.isSelected() || box2b.isSelected()) &&
(box3a.isSelected() || box3b.isSelected()) &&
(box4a.isSelected() || box4b.isSelected()) &&
(box5a.isSelected() || box5b.isSelected()))
{
//true stuff
}
else
{
new Error("You must select an answer at all the questions");
}
You should never shouldn't test for true with ==. It is poor style, better to just use the return value from isSelected()
if ((box1a.isSelected() == true || box1b.isSelected() == true) &&
(box2a.isSelected() == true || box2b.isSelected() == true) &&
(box3a.isSelected() == true || box3b.isSelected() == true) &&
(box4a.isSelected() == true || box4b.isSelected() == true) &&
(box5a.isSelected() == true || box5b.isSelected() == true)) {
//DO SOMETHING IF TRUE
}
else {
new Error("You must select an answer at all the questions");
}
No looping needed ^_^
why don't you use radio button (with a default radio button checked) in this case ?
A general strategy would be something like this:
bool flag = true;
do{
//search for input
if (/*the input is valid*/)
flag = false;
}while (flag);
But if you hard code so many options, you might have the wrong design. Try something like a radio button like Jerome C. suggested.
if(!box1a.isSelected() && !box1b.isSelected()) {
// You must select an answer at all the questions
}
else if (box1a.isSelected() && box1b.isSelected() && box2a.isSelected() && box2b.isSelected() && box3a.isSelected() && box3b.isSelected() && box4a.isSelected() && box4b.isSelected() && box5a.isSelected() && box5b.isSelected()) {
// with some other things he does when it is true.
}
A few points to note here.
Avoid using class names like Error as they're normally used for genuine java.lang.Error logic.
If you have a boolean, you don't need to use a == operator.
Not sure why you want a while-loop. If you are thinking that the user must "stay in the loop" while the your condition (all 5 questions answered) is not met, then it is unnecessary. The Event Dispatch Thread (EDT) will continue running the "loop" for you.
On the other hand, if you are looking for a compact way to verify all of your checkboxes, you can change how they are declared from (assuming) javax.swing.JCheckbox box1a; etc. to either a fixed array or an ArrayList which you can then iterate over with a for-loop.

In Java, what are the boolean "order of operations"?

Let's take a simple example of an object Cat. I want to be sure the "not null" cat is either orange or grey.
if(cat != null && cat.getColor() == "orange" || cat.getColor() == "grey") {
//do stuff
}
I believe AND comes first, then the OR. I'm kinda fuzzy though, so here are my questions:
Can someone walk me through this statement so I'm sure I get what happens?
Also, what happens if I add parentheses; does that change the order of operations?
Will my order of operations change from language to language?
The Java Tutorials has a list illustrating operator precedence. The equality operators will be evaluated first, then &&, then ||. Parentheses will be evaluated before anything else, so adding them can change the order. This is usually pretty much the same from language to language, but it's always a good idea to double check.
It's the small variations in behavior that you're not expecting that can cause you to spend an entire day debugging, so it's a good idea to put the parentheses in place so you're sure what the order of evaluation will be.
Boolean order of operations (in all languages I believe):
parens
NOT
AND
OR
So your logic above is equivalent to:
(cat != null && cat.getColor() == "orange") || cat.getColor() == "grey"
The expression is basically identical to:
if ( (cat != null && cat.getColor() == "orange") || cat.getColor() == "grey") {
...
}
The order of precedence here is that AND (&&) has higher precedence than OR (||).
You should also know that using == to test for String equality will sometimes work in Java but it is not how you should do it. You should do:
if (cat != null && ("orange".equals(cat.getColor()) || "grey".equals(cat.getColor()))) {
...
}
ie use the equals() methods for String comparison, not == which simply does reference equality. Reference equality for strings can be misleading. For example:
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
First, your if statement contains three main expressions:
cat != null
cat.getColor() == "orange"
cat.getColor() == "grey"
The first expression simply checks whether cat is not null. Its necessary otherwise the the second expression will get executed and will result in a NPE(null pointer excpetion). That's why the use of && between the first and second expression. When you use &&, if the first expression evaluates to false the second expression is never executed.
Finally you check whether the cat's color is grey.
Finally note that your if statement is
still wrong because if cat is
null, the third expression is still
executed and hence you get a null
pointer exception.
The right way of doing it is:
if(cat != null && (cat.getColor() == "orange" || cat.getColor() == "grey")) {
//do stuff
}
Check the order of parenthesis.
Yeah && is definitely evaluated before ||. But I see you are doing cat.getColor() == "orange" which might give you unexpected result. You may want to this instead :
if(cat != null && ("orange".equals(cat.getColor()) || "grey".equals(cat.getColor()))) {
//do stuff
}
Order of Operation is not what you need, you need boolean algebra, this includes boolean functions. Maxterms/minterms, Gray code, Karnaugh tables, diodes,transistors, logic gates, multiplexers, bitadders, flip flops...
What you want is to implement boolean "logic" on computers or virtual machines. With "order of operations" you may refer something about physics like managing delays on logic gates (OR, if) nanoseconds intervals?

Categories

Resources