Learn
Conditional Expressions
Logical Operators

Logical operators evaluate the relationship between two or more Boolean expressions and return a true or false value. There are several operators that we can use: &&, ||, and !.

The logical AND operator (&&) returns true if and only if the expressions on both sides of the operator return true.

var isSunny = true var temp = 85 if (isSunny && temp > 80) { println("Wear sunglasses.") } // Prints: Wear sunglasses.

Since isSunny is true and temp has a value above 80, the expression inside the condition becomes true so Wear sunglasses. is outputted to the terminal.

The logical OR operator (||) will only return true if at least one of the Boolean expressions being compared has a true value.

var isSnowing = false var temp = 38 if (isSnowing || temp < 40 ) { println("Wear a scarf.") } // Prints: Wear a scarf.

Even though the first value isSnowing is false, the full expression will return true because the other Boolean expression, temp < 40, is true.

The logical NOT operator, denoted by !, will evaluate the truth value of a Boolean expression and then return its inverse. For example:

var isSnowing = true println(!isSnowing) // Prints: false

We can even add ! before a multi-part expression. By adding the ! operator to our previous code example, the Boolean expression now returns a false value:

var isSnowing = false var temp = 38 if (!(isSnowing || temp < 40)) { println("Wear a scarf.") } // This program will not have any output.

Note: The truth tables displayed on the right side of the screen display the various outcomes of Boolean expressions being evaluated using logical operators.

Instructions

1.

Take a look at Logic.kt.

Replace each __ with a logical operator so that each expression evaluates to true and 4 statements are printed to the terminal.

Use the truth tables on the right side of the screen to help make a decision about which logical operator to use.

Note: Feel free to adjust the size of the code editor to get a better view of the code.

Folder Icon

Take this course for free

Already have an account?