Difference between AND and OR

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

if ( fiber >= 4 || foam >= 3 )
  System.out.println("House passes the code requirements!" );
else
  System.out.println("House fails." );

Difference between AND and OR

Here is what would happen if a house had 6 inches of fiberglass batting and 0 inches of plastic foam:

fiber >= 4 || foam >= 3
---------    ---------
  true          false
   ---------------
        true

One true is enough.

AND is different from OR. Both of them combine Boolean values ( true/false values ) into one Boolean value. But each does this in a different way:

  • All the values AND combines must be true to get a true.
  • At least one of the values OR combines must be true to get a true.

The operation of AND and OR can be displayed in a truth table. In the table, A and B are operands. They stand for true/false values or expressions that yield true/false values. For example, A could stand for a relational expression such as memory > 512 or a string comparison like phrase.equals( "quit" ).

A B A && B A || B
F F F F
F T F T
T F F T
T T T T

Each row of the truth table shows how logical operators combine the true/false values of operands. For example, row one says that if A is false and B is false, then A && B is false also A || B is false.

Row three says that if A is true and B is false, then A && B is false also A || B is true.

All possible truth values of the operands A and B are listed in the left two columns. Each operand can take the value true or the value false, so there are four possible combinations of values for the two operands.

QUESTION 21:

Pick true or false for each of the following:

5 > 2 || 12 <= 7      
5 > 2 && 12 <= 7      
3 == 8 || 6 != 6      
3 == 8 && 6 != 6      

(Remember that != means "not equal.")