Logical Operators (and Booleans)


Collapse Content

In previous nodes, we showed how you can use if, while and for statements to execute code only when a certain condition is true. This works fine if you just care about checking one condition, but sometimes you will want to run code when either A OR B is true, or only when A AND B are true.

In such cases, you will want to use the logical operators "And" and "Or". In Java they are written as && and ||. For example:

int a = 5;
int b = 7;
boolean aLargish;
boolean bLarger;            //declare a true/false variable

bLarger =  b > a && a > 0;  //true, since both true.
aLargish =  a > b || a > 0; //true, since a>0 and it's an OR statement
boolean both =  aLargish && bLarger; //true again!

In the above code, the results of the first comparison was stored in the boolean variable bLarger. As in the previous node, this could then be used in a conditional statement :

 if(bLarger){
   //do something...
 } 

Alternatively, you can put the expression itself in the if-statement without using a variable:

 if(b > a && a > 0){
   //do something...
 } 

Note that:

  • a && b will return true only when BOTH a AND b are true.
  • a || b will return true when either a AND/OR b are true.

Challenge
As briefly mentioned in About Programming, computers ultimately calculate just by doing simple logical operation like AND and OR on Logic Gates. While these gates are physical parts of a computer, you can simulate them in software. The NAND gate is a logical gate that returns false only when both its inputs are true. In other cases it returns true. You will simulate a NAND gate in this challenge. Try to do this challenge without using any if statements.

Challenge

You will be given two integer inputs, a and b. Simulate a NAND gate by returning a boolean false only if both inputs are equal to 1, and returning true in all other cases.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

Contact Us
Sign in or email us at [email protected]