Complex Conditionals¶

What if you want two things to be true before the body of the conditional is executed? Use && as a logical and to join two Boolean expressions and the body of the condition will only be executed only if both are true. For example, what if you want to go out and your mom said you could if you clean your room and do your homework?

if (cleanedRoom && didHomework) System.out.println("You can go out");
else System.out.println("No, you can't go out");


What if it is okay if only one of two things is true? Use || as a logical or to join two Boolean expressions and the body of the condition will be executed if one or both are true. For example, your Dad might say you can go out if you can walk or he doesn’t need the car.

if (walking || carIsAvailable) System.out.println("You can go out");
else System.out.println("No, you can't go out");


The following table (also called a truth table) shows the result for P && Q when P and Q are both expressions that can be true or false. As you can see below the result of P && Q is only true if both P and Q are true.

P Q P && Q
true true true
false true false
true false false
false false false

The following table shows the result for P || Q when P and Q are both expressions that can be true or false. As you can see below the result of P || Q is true if either P or Q is true. It is also true when both of them are true.

P Q P || Q
true true true
false true true
true false true
false false false

5-2-1: What is printed when the following code executes and x has been set to zero?

if (x > 0 && (y / x) == 3) System.out.println("first case");
else System.out.println("second case");


if (x > 0 || (y / x) == 3) System.out.println("first case");