3️⃣

6.3 Logical Operators

Chapter Table of Contents

🤔
Ch. 6 Conditionals

Section Table of Contents

Logical operators are binary operators that allow you to combine different boolean expressions (a boolean expression is basically something that can evaluate to either true or false). Look at the tables below to learn about them. The tables are divided into 2 sections: a truth table, and examples. For the truth table section, p refers to any boolean expression.

For a deeper explanation, you can also watch this Crash Course video (note: don’t worry too much about the logic gates and transistors — focus on what AND, OR, XOR, and NOT mean conceptually).

Logical Operators

OperatorNameEvaluates True ONLY ...
&&
logical AND
Both Conditions are true
||
logical OR
At least 1 Condition is true
^
logical XOR (exclusive OR)
Exactly 1 Condition is true

image

Credit: Y. Daniel Liang, Introduction to Java Programming (Comprehensive Version), 10th ed.

⚠️

NOTE: There is an error in the first example. It should say that the overall expression is false because (age > 28) is false.

image

Credit: Y. Daniel Liang, Introduction to Java Programming (Comprehensive Version), 10th ed.

image

Credit: Y. Daniel Liang, Introduction to Java Programming (Comprehensive Version), 10th ed.

There is also a unary logical operator, the logical NOT.

Untitled

OperatorNameWhat it does
!
Logical NOT
Switches the current boolean value to the other value

image

Credit: Y. Daniel Liang, Introduction to Java Programming (Comprehensive Version), 10th ed.

Practice

Logic

Given the code in the practice template, predict what the output of this program will be. Write your answers as comments on the program next to the print statements.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.