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
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.

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.

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.

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, anint(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.