Conditionals

Conditionals

Conditionals take an expression, which is code that evaluates to determine a value, and checks if it is true or false. If it’s true, we can tell our program to do one thing — we can even account for false to do another.

As we write more complex programs, conditionals allow us to address multiple scenarios and make our programs more robust.

If Statement

An if statement executes a block of code when a specified boolean expression is evaluated as true; otherwise, the block of code will be skipped.

Loading...

Else

An else clause can be added to an if statement.

The else statement executes a block of code when the condition inside the if statement is false:

  • If the condition evaluates to true, code in the if part is executed.
  • If the condition evaluates to false, code in the else part is executed.

The else statement is always the last condition.

Loading...

Else If

else if statements can be chained together to check multiple conditions. Once a condition is true, a code block will be executed and the conditional statement will be exited.

There can be multiple else if statements in a single conditional statement.

Loading...

Nested Conditional Statements

A nested conditional statement is a conditional statement nested inside another conditional statement. The outer conditional statement is evaluated first; if the condition is true, then the nested conditional statement will be evaluated.

Loading...

The output would be:

Loading...
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn Java on Codecademy