If

Use if, if-else and if-else if-else to run a block of code only when a condition is true, or to pick one block out of several.

Novice · Java · Updated

By

All programming languages allow us to execute code only if certain conditions are met. Making decisions is what programming logic is all about.

A basic if statement executes code if the test is true and does not execute any code if it is false.

Flowchart of an if: when the decision is yes, the action runs; when it is no, the program skips straight to the end

int availableCash = 20;

if(availableCash > 10)
{
    System.out.println("You can eat out");
}

If - Else

The if-else statement has two code blocks. Only one of them will execute depending on the condition.

Flowchart of an if-else: yes runs Action 1, no runs Action 2, and then both paths continue to the end

int availableCash = 15;

if(availableCash > 20)
{
    System.out.println("You can eat at Slice Palace Pizza");
}
else
{
    System.out.println("You can eat at Burger Barn");
}

If - Else If - Else

The if-else if-else statement allows multiple code blocks. Only one of them runs: the first one whose condition is true, or the else block if none is.

Flowchart of an if-else if-else: Decision 1 yes runs Action 1; otherwise Decision 2 yes runs Action 2; otherwise Action 3 runs

int availableCash = 15;

if(availableCash > 50)
{
    System.out.println("You can eat at Riverside Steakhouse");
}
else if(availableCash > 20)
{
    System.out.println("You can eat at Slice Palace Pizza");
}
else
{
    System.out.println("You can eat at Burger Barn");
}

Do it: pick tonight's movie plan

It's movie night, and what you can do depends on how much cash you have. Write a function that picks the plan.

The function gets one value:

  • availableCash: how many dollars you have, an int (20).

The plans, checked from the top:

Cash The plan
$30 or more "Movie and popcorn"
$15 up to $29 "Movie only"
less than $15 "Movie at home"

For example, with $20:

Check With $20
Is it $30 or more? No: 20 is less than 30
Is it $15 or more? Yes: the plan is "Movie only"

So moviePlan(20) returns "Movie only".

Your job: write the function String moviePlan(int availableCash) so it returns the plan for any amount of cash.

  • Return "Movie and popcorn" for $30 or more.
  • Return "Movie only" for $15 up to $29.
  • Return "Movie at home" for less than $15.
  • The ends count: exactly $30 gets "Movie and popcorn", and exactly $15 gets "Movie only".

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets