Courseiva
1Z0-811Chapter 6 of 16Objective 2.3

Making Decisions with if, else, and switch Statements

Making decisions is the heartbeat of any useful program. A computer program that just runs line by line without ever choosing between options is about as useful as a light switch that is always on – it can't react to the world. For someone studying the 1Z0-811 exam, mastering 'if' and 'switch' is non-negotiable because these statements are how you tell the computer to behave differently based on different inputs, and the exam will directly test your ability to write and trace this logic.

12 min read
Beginner
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture Making Decisions with if, else, and switch Statements

The Vending Machine Analogy

When you approach a vending machine, you first insert your money. That action leads to a series of decisions the machine must make. The machine checks if your payment is enough, and then it lets you choose.

Imagine a vending machine that only sells crisps. You press the button for salt and vinegar. The machine checks its internal inventory: if there are salt and vinegar crisps, it dispenses them. That is an 'if' statement. But what if you pressed the button for prawn cocktail and the machine is out? The machine doesn't just freeze. It has a fallback plan. If prawn cocktail is unavailable, it checks the next row. If that is also empty, it displays 'Out of stock'. That chain of checks is like an 'if-else if-else' structure in Java. The vending machine keeps asking yes-or-no questions until it finds a valid option or runs out of choices.

Now, a switch statement is like a multi-button vending machine where each button corresponds to a specific flavour. You press one button. The machine doesn't ask a series of yes-or-no questions. It directly maps your single button press to a single action: 'Button A means salt and vinegar. Button B means cheese and onion. Button C means plain.' If you press a button that isn't programmed, nothing happens. That direct, one-step decision is a switch statement. The analogy maps precisely: the vending machine's internal logic decides what to do based on the value you provide (the button press). It handles mismatches (no such snack) with a default action, just like Java's 'default' case.

How It Actually Works

In Java, a program normally runs from top to bottom, executing every line of code in order. This is called 'sequential execution'. But a program that cannot make choices is useless. You need the program to behave one way when a condition is true and another way when it is false. That is where conditional statements come in.

An 'if' statement is the simplest decision-maker. It checks a condition – which must be a boolean expression (something that evaluates to either 'true' or 'false'). If the condition is true, the block of code inside the if statement runs. If the condition is false, that block is skipped entirely.

For example: int age = 20; if (age >= 18) { System.out.println("You can vote."); }

Here, the condition is 'age >= 18'. Since 20 is greater than or equal to 18, the condition is true, so the message prints. If age were 16, the condition would be false and the message would not print.

An 'if-else' statement adds a second path. When the condition is false, the code in the 'else' block runs instead. This provides two mutually exclusive paths: one for true, one for false.

int temperature = 30; if (temperature > 25) { System.out.println("It is hot outside."); } else { System.out.println("It is not hot outside."); }

The 'if-else-if' ladder (also called 'else if') allows you to check multiple conditions in sequence. The program checks each condition from top to bottom. The first condition that evaluates to true causes its code block to run, and then the rest of the ladder is skipped. If none of the conditions are true, the final 'else' block runs (if it is provided).

int score = 75; if (score >= 90) { System.out.println("Grade: A"); } else if (score >= 80) { System.out.println("Grade: B"); } else if (score >= 70) { System.out.println("Grade: C"); } else { System.out.println("Grade: F"); }

This prints 'Grade: C' because the first two conditions are false, and the third condition (score >= 70) is true. Note that the order of conditions matters. If you put 'score >= 70' before 'score >= 90', then a score of 95 would incorrectly print 'Grade: C'.

A 'switch' statement is a more efficient way to handle many possible values for a single variable. Instead of a long chain of 'if-else if' statements, a switch statement compares the value of a variable (called the 'selector') against a list of 'case' labels. The variable used in a switch must be one of the following types: byte, short, char, int, String, or an enum. When the switch executes, it jumps directly to the 'case' label that matches the selector's value and executes the code from that point until it hits a 'break' statement or the end of the switch block.

String day = "Monday"; switch (day) { case "Monday": System.out.println("Start of work week"); break; case "Friday": System.out.println("End of work week"); break; case "Saturday": case "Sunday": System.out.println("Weekend!"); break; default: System.out.println("Midweek"); break; }

If you forget the 'break' statement after a case, the program will 'fall through' to the next case and execute its code, regardless of whether it matches. This is called 'fall-through' and is a common source of bugs. The 'default' case is optional. It runs if none of the specified cases match the selector. It is like the 'else' in an if-else structure.

The main advantage of a switch over a long if-else-if ladder is readability and performance. For many related comparisons on the same variable, switch is clearer and can be faster because the JVM (Java Virtual Machine) can optimise it using a 'lookup table' instead of evaluating multiple conditions one by one. However, a switch can only check for exact equality, not for ranges or conditions like 'greater than'. For those cases, you must use if-else.

Flowchart showing the decision path for an if-else-if-else structure and a switch structure.

Walk-Through

1

Define a Boolean Condition

Start by writing the keyword 'if', followed by parentheses. Inside the parentheses, place an expression that evaluates to true or false. This could be a comparison like 'temperature > 25' or a boolean variable like 'isRaining'. If the expression is true, the next block of code will run.

2

Write the If Body

After the parentheses, open a curly brace '{'. Write the code that should run only when the condition is true. Close the brace '}'. If the block contains only a single statement, the braces are optional, but omitting them can lead to bugs. For clarity, always use braces in this step.

3

Add the Else Clause (Optional)

After the closing brace of the if block, add the keyword 'else' and another block of code in curly braces. This block runs only when the condition in the if is false. This creates two possible paths. You can chain multiple 'else if' conditions between the if and the final else to check multiple sequential conditions.

4

Choose the Switch Variable

If your decision is based on a single variable that could match one of many distinct values, consider using a switch. Write the keyword 'switch' and put the variable inside parentheses. This variable must be one of the allowed types: byte, short, char, int, String, or an enum.

5

Define Cases and Add Break

Inside the switch block's curly braces, write 'case' followed by a constant value and a colon. Write the code that should run for that case, and then write 'break;' to exit the switch. If you omit 'break', the execution will fall through to the next case. Repeat for each possible value.

6

Provide a Default Case (Recommended)

Add a 'default:' case at the end of your switch block. This catches any value that does not match any of your explicit cases. It is good practice to include a default even if you think you have covered all cases, because future changes to the data might introduce unexpected values.

What This Looks Like on the Job

An IT professional uses these decision-making structures constantly. Consider a junior developer working at a bank, building a simple ATM withdrawal system. The system must respond differently based on the user's input and account status.

First, the user enters their desired withdrawal amount. The code uses an 'if' statement to check if the amount is a multiple of the available denominations (say, $10). If it is not a multiple, the ATM prints an error message and does not proceed.

if (amount % 10 != 0) { System.out.println("Please enter an amount that is a multiple of 10."); return; // stop here }

Next, the system checks if the withdrawal amount exceeds the daily limit. This is another 'if' statement.

if (amount > dailyLimit) { System.out.println("Withdrawal exceeds your daily limit."); return; }

Then, the system checks the account balance. If the balance is sufficient, it dispenses cash. If not, it prints an insufficient funds message. This is a classic 'if-else'.

if (balance >= amount) { balance = balance - amount; System.out.println("Please take your cash."); } else { System.out.println("Insufficient funds."); }

Now imagine the ATM has a menu option for 'Account Type'. The user selects 'Savings', 'Checking', or 'Business'. The developer uses a 'switch' statement to apply different interest rates or rules for each type.

switch (accountType) { case "Savings": interestRate = 0.04; break; case "Checking": interestRate = 0.01; break; case "Business": interestRate = 0.02; break; default: System.out.println("Invalid account type."); break; }

The developer also uses 'if-else' to handle edge cases. For example, if the user tries to withdraw more than $500 in cash, the ATM prints a warning and asks for confirmation before proceeding.

if (amount > 500) { System.out.println("Large withdrawal. Confirm by pressing Y."); // wait for user confirmation }

In a real professional environment, the developer would also use 'if' statements nested inside other 'if' statements (nested ifs) to handle complex business rules. For instance, if the user is a high-value customer (a 'premium' status), the daily limit for withdrawals is higher. The code would look like:

if (customerStatus == "Premium") { if (amount > 5000) { System.out.println("Requires manager approval."); } else { // allow withdrawal up to $5000 } } else { if (amount > 1000) { System.out.println("Exceeds standard limit."); } else { // allow withdrawal up to $1000 } }

This real-world scenario shows that without 'if', 'else', and 'switch', the ATM would be a dumb machine that either always gives money or never gives money. The decision-making logic is what makes the program intelligent and responsive to the user's needs.

How 1Z0-811 Actually Tests This

The 1Z0-811 exam tests your understanding of 'if', 'if-else', 'if-else-if', and 'switch' statements in a very specific way. You will not be asked to write a full program from scratch. Instead, you will be given a short snippet of code and asked to determine its output, or you will be given a description and asked which code fragment correctly implements it.

Here are the exact concepts the exam loves to test:

Boolean expressions: The condition inside an 'if' must evaluate to a boolean. The exam will trick you by putting a non-boolean value, like an integer, inside the parentheses. In Java, 'if(5)' is not valid. A variable like 'int x = 5; if(x)' will cause a compilation error. The exam expects you to know this.

The difference between '=' (assignment) and '==' (comparison): A classic trap. Beginners often write 'if (score = 100)' intending to compare, but this assigns 100 to score and then uses score as the condition. Since score is now 100, it is not a boolean, so the code will not compile. The exam will have a snippet with 'if (flag = true)' where flag is a boolean, and this compiles (because the assignment yields true), but it is almost certainly not the programmer's intention. The exam tests whether you spot the difference.

Switch variable types: The exam requires you to know which types can be used in a switch. You must memorise that switch works with 'int', 'byte', 'short', 'char', 'String' (since Java 7), and 'enum'. A switch does NOT work with 'long', 'float', 'double', or 'boolean'. The exam will give you a switch using a 'long' and ask if it compiles – the answer is no.

Break statements and fall-through: The exam frequently tests your understanding of fall-through. They give you a switch with no 'break' after a case, and you must trace the execution. If case 'A' outputs something and falls through to case 'B', both outputs will appear. The default case also participates in fall-through if placed non-traditionally.

Default placement: The 'default' case does not have to be the last case in the switch. You can put it in the middle. The exam may place default in an unexpected position and ask you what prints. Remember that execution still jumps to the matching case and falls through from there.

The else-if ladder only executes one branch: The exam will give you a scenario where multiple conditions in an else-if ladder are true. You must remember that only the first true condition's block executes, and then the ladder exits. The subsequent 'else if' and 'else' are ignored.

Curly braces: The exam tests whether you know that for a single statement inside an if or else, the curly braces are optional. But if you omit them, only the very next line is part of the if block. The exam will show misleading indentation where the next line is indented but actually is not inside the if.

Common exam question patterns: - 'Given the following code, what is the output?' - 'Which of these code fragments correctly implements the requirement: if the user is an admin, show the menu; otherwise, show the login page?' - 'Does this code compile? If not, why?'

To prepare, memorise the 'switch' variable types, the fact that 'if' requires a boolean, and the behaviour of fall-through. Practise tracing short code snippets by hand. Many students slip on the misuse of '==' vs '=' or on the fact that an empty 'if' body (if (x==5) ; ) is valid but does nothing.

Key Takeaways

An 'if' statement executes its code block only if the condition inside its parentheses is true, and the condition must be a boolean expression.

An 'if-else' statement provides two mutually exclusive paths: one for a true condition and one for a false condition.

In an 'if-else-if' ladder, only the first condition that evaluates to true will have its code run; all subsequent conditions are ignored.

A 'switch' statement can be used instead of a long if-else-if chain when you are comparing a single variable against many exact values.

You must include a 'break' statement after each case in a switch, unless you intentionally want fall-through to the next case.

Switch statements support only byte, short, char, int, String, and enum data types as the selector variable.

The 'default' case in a switch is optional and runs if no other case matches, regardless of where it appears in the switch block.

Using '=' inside an if condition instead of '==' causes an assignment, which will either cause a compilation error or lead to unintended logic.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

if-else-if Ladder

Can evaluate complex conditions with ranges, comparisons, and logical operators.

Evaluates conditions sequentially from top to bottom.

Works with any data type that supports boolean expressions.

Can be harder to read when there are many conditions.

switch Statement

Can only check for exact equality against constant values.

Jumps directly to the matching case without sequential checks.

Works only with byte, short, char, int, String, and enum types.

More readable and concise when comparing a single variable against many values.

= (Assignment Operator)

Used to assign a value to a variable.

Changes the value of the variable permanently.

In an if condition, if the assigned value is not boolean, it causes a compilation error.

== (Comparison Operator)

Used to compare two values for equality.

Does not change any variable's value.

In an if condition, it yields a boolean result (true or false) as required.

Single if Statement

Provides one code path that runs only when the condition is true.

Does nothing when the condition is false.

The condition must produce a boolean value.

if-else Statement

Provides two mutually exclusive code paths: one for true and one for false.

Always executes exactly one of the two blocks.

The condition must produce a boolean value.

Watch Out for These

Mistake

You can use any data type in a switch statement.

Correct

Switch only works with byte, short, char, int, String, and enum types. It does not work with long, float, double, or boolean.

Beginners assume that if you can compare a value with ==, then it should work in a switch. But switch is implemented differently under the hood and only supports a restricted set of types.

Mistake

If two conditions in an if-else-if ladder are true, both blocks will execute.

Correct

Only the first true condition's block runs. The rest of the ladder is skipped entirely.

People are used to sequential thinking where every line runs. The ladder is designed to stop at the first match, which is unintuitive to newcomers.

Mistake

If you don't write a default case, the switch will do nothing if no case matches.

Correct

That is actually correct for a switch – if no case matches and there is no default, nothing happens. But the misconception is that this is a bug. It is intentional and valid behaviour.

Beginners often think every switch must handle all possibilities, but Java allows you to ignore unmatched values silently. It is a feature, not an error.

Mistake

Using 'else' is required after every 'if'.

Correct

An 'if' can exist without an 'else'. The 'else' part is optional. If you only need to do something when a condition is true, and nothing when it is false, you can just use 'if' alone.

Tutorials often show if-else as a pair, so beginners think they must always include the else. This leads to writing unnecessary empty else blocks.

Mistake

The condition in an if statement can be any expression that evaluates to a number or a string.

Correct

The condition must be a boolean expression (true or false). Number or string expressions will cause a compilation error unless they are used in a comparison that yields a boolean.

Other programming languages like C or Python allow numbers to stand in for true/false, but Java is strict. Beginners from other languages or self-taught expectations carry that assumption.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

Can I use a 'String' variable in a switch statement in Java?

Yes, from Java 7 onwards, you can use a String variable in a switch statement. The comparison is case-sensitive, so 'Monday' and 'monday' are treated as different values.

What happens if I forget the 'break' in a switch case?

The program will 'fall through' and execute the code in the next case, regardless of whether that case's label matches the selector. This continues until a 'break' is encountered or the switch ends.

Is the 'else' part mandatory after an 'if'?

No, the 'else' part is entirely optional. You can have an 'if' statement with no 'else'. If the condition is false and there is no else, the program simply skips the if block and continues with the next line of code.

Can I use a 'long' or 'double' variable in a switch statement?

No. Switch statements in Java only support 'int', 'byte', 'short', 'char', 'String', and 'enum' types. Using 'long', 'float', or 'double' will cause a compilation error.

What is the difference between 'if-else-if' and 'switch'?

An 'if-else-if' ladder can evaluate conditions that involve ranges, comparisons like 'greater than', or combinations of variables. A 'switch' can only check for exact equality against constant values, but it is often more readable and faster for that specific use case.

Does Java evaluate all conditions in an if-else-if ladder?

No. Java evaluates the conditions from top to bottom. As soon as it finds a true condition, it runs that block and skips the rest of the ladder. This is called 'short-circuit evaluation' in the context of the ladder.

Keep going

You've finished Making Decisions with if, else, and switch Statements. Continue through the 1Z0-811 study guide to build a complete picture of the exam.

Done with this chapter?