Learn
Conditional Expressions
if Expression

An if expression is a conditional that executes a body of code only when a specified Boolean value returns true.

Assume we had a Boolean variable called raining:

var raining = true

We can use an if expression to evaluate the value of raining to determine whether or not we execute some code:

if (raining) { println("Bring an umbrella.") }
  • The expression starts with the keyword, if.
  • A pair of parentheses contains a condition (raining) that evaluates to either true or false.
  • Following the condition is a pair of brackets { and } that holds a block of code.

The code contained within the code block of the if expression will only execute if the condition is true; otherwise, that code block will be ignored.

When we run the program above, we get the following output:

Bring an umbrella.

The value of raining inside of the if expression is true; therefore, the instruction println("Bring an umbrella.") gets executed.

Instructions

1.

Your neighbor keeps forgetting what day the garbage gets picked up. You decide to create a small program to remind them when to take their garbage out.

Create an if expression that checks if the value of isTuesday is true.

Inside the if expression, create a println() statement that outputs "Take out the trash".

Folder Icon

Take this course for free

Already have an account?