Concepts / The if-else Statement in Java

The if-else Statement in Java

The if statement takes the form if ( boolean-expression ) statement-1 else statement-2.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

Decisions a Program Must Make

Programs constantly face decisions. A payment either goes through or it does not. A number is either negative or it is not. Java handles decisions like these with branching statements, and the if statement is the first of the two branching statements the language provides.

Before reading any syntax, try to picture the situation as a question the program asks: given a condition, which of two actions should run? Keep that question in mind, because the syntax is simply a precise way of writing it down.

What do you think happens?

In the code below, score is 45. Which line gets printed?

  • Pass

  • Fail

  • Both lines

  • Neither line

Reveal answer
Answer:

Fail

The boolean expression score >= 60 is false for 45, so the statement after the else runs and the statement after the if is skipped. The trace in the next section follows this step by step.

Tracing a Single Decision

Here is a small program that makes one decision. Before reading the explanation, follow the program yourself: find the value of score, evaluate the condition, and decide which line runs.

Code walkthrough
int score = 45;
if (score >= 60)
    System.out.println("Pass");
else
    System.out.println("Fail");
  1. 1
    Line 1 stores 45 in score.
  2. 2
    Line 2 evaluates the boolean expression score >= 60. For 45 this is false.
  3. 3
    Because the expression is false, the statement after the if (the Pass print) is skipped.
  4. 4
    The else part is present, so its statement runs, which prints Fail.
  5. 5
    The program then continues with whatever follows the if-else. Nothing else follows here, so it ends.
  • score is set to 45 before the decision
  • The boolean expression score >= 60 is evaluated and yields false
  • The false result selects the statement after else
Output
Fail
score = 45score >= 60evaluates to falsePrint PassskippedProgram continuesPrint Failexecutedtruefalse
For score equal to 45, which statement executes, which is skipped, and where does the outcome come from?

The diagram is a map of the same decision. The condition is checked first. Its result selects one path, the Pass print is skipped, and only the Fail print executes. The outcome is traceable to one place: the boolean expression evaluated to false for this input.

Parts of the if-else Template

The source gives the if statement as a general template rather than a complete program. The template takes the form if ( boolean-expression ) statement-1 else statement-2. The angle-bracket style names are placeholders: each one stands for something you fill in with real code.

ifkeyword that starts thestatement( boolean-expression)the condition: true orfalsestatement-1runs when the condition istrueelseoptional keyword for thesecond pathstatement-2runs when the condition isfalse
Which part of if ( boolean-expression ) statement-1 else statement-2 is the condition, which is the true-branch statement, and which is the optional else part?

Read the template from left to right. The keyword if comes first, followed by a boolean expression inside parentheses. The boolean expression is the condition: it evaluates to either true or false. The statement that follows the parentheses is statement-1. If the optional else part is present, it consists of the word else and the statement that follows it, which is statement-2.

Why It Is a Two-Way Branch

The if statement is described as a two-way branch because the boolean expression decides which statement runs, and there are exactly two possible destinations. When the expression yields true, statement-1 is taken. When an else part exists and the expression yields false, statement-2 is taken.

Reach if statementEvaluateboolean-expressionyields true or falseRun statement-1taken when trueContinue after theif-elseRun statement-2taken when falsetruefalse
After the boolean expression is evaluated, which of the two paths does control take, and how do both paths rejoin after the statement finishes?

The map also shows how the two paths meet again. Whichever statement ran, the program then continues with the code that follows the whole if-else. The decision selects a path for that one step, and the program then carries on as a single sequence.

Omitting the else Part

Many decisions only need one action. If the condition is false, the program should simply carry on. Because the else part can be omitted, the if statement handles this case directly. The shorter form consists of the if keyword, the parenthesized boolean expression, and statement-1.

Code walkthrough
int temperature = 12;
if (temperature < 0)
    System.out.println("Freezing");
System.out.println("Checked temperature");
  1. 1
    temperature is set to 12.
  2. 2
    The boolean expression temperature < 0 is false.
  3. 3
    statement-1 (the Freezing print) is skipped, and nothing else happens inside the if statement.
  4. 4
    The program continues to the line after the if statement, which prints Checked temperature.
  • No else part is written
  • The condition is false for 12
  • The final print is outside the if statement
Output
Checked temperature
Key point

When an if statement has no else part and its expression is false, statement-1 is skipped and the program continues with whatever follows the if statement.

Using Blocks for Several Statements

A single statement is often not enough for a real decision. You might need to update several variables or print several messages when a condition holds. The statements inside an if statement can be blocks. A block lets you place several statements where the grammar expects one. In Java, a block is written between curly braces, so a block used as statement-1 or statement-2 groups several statements into one branch.

Worked example

A block on each branch

Print two messages when score is at least 60, and two different messages otherwise, for score = 45.

  1. 1
    Set the input

    score is 45, so the condition score >= 60 is false.

  2. 2
    Select the branch

    The false result selects the else part, so the block after else is the one that runs.

  3. 3
    Run the whole block

    Both statements inside that block execute in order, because the braces group them as one branch.

  4. 4
    Skip the other block

    The block after the if keyword is skipped entirely, so neither of its messages prints.

Result

The output is Fail, followed by Try again next term.

java
Output
Fail
Try again next term
Notes on the code
  • Each branch is a block in curly braces
  • The whole block after else runs when the condition is false

Tracing an Unexpected Result

When a program produces a result you did not expect, an if statement is a common place to look. Start by asking which path the program actually took. Then check the boolean expression: did it evaluate to the value you assumed? If the expression was right and the wrong statement ran, check whether the statements sit in the correct slots.

Worked example

Locating a statement that always runs

The programmer expects big to print only when x is greater than 5. With x = 3, the program prints big anyway. Find where the unexpected output comes from.

  1. 1
    Ask which path ran

    The output shows that the print statement ran, so the program took the path that executes it.

  2. 2
    Check the expression

    x > 5 is false for x = 3, so the expression yielded the value the programmer assumed.

  3. 3
    Check the slots

    A semicolon directly after the parentheses makes statement-1 an empty statement. The false result skips that empty statement.

  4. 4
    Find the real culprit

    The println on the next line is a separate statement outside the if, so it runs every time.

Result

The bug is the stray semicolon. Removing it makes the println part of the if statement, so nothing prints for x = 3.

java
Output
big
Notes on the code
  • The semicolon after the parentheses ends the if statement
  • println runs as its own statement, not as statement-1

Mistakes That Cause Unexpected Output

  • Common mistake

    Placing a semicolon directly after the if condition

    What it looks like
    if (x > 5); followed by a println on the next line
    Why it fails

    The semicolon makes statement-1 an empty statement, so the if controls nothing and the following println always runs.

    Do this instead

    Remove the semicolon so the intended statement sits directly in the slot after the parentheses.

  • Common mistake

    Expecting several statements after an if to be conditional without braces

    What it looks like
    if (x > 5) println(big); followed by println(done); on the next line
    Why it fails

    Without braces, statement-1 is only the single statement right after the parentheses. The second println is outside the if.

    Do this instead

    Wrap every statement that belongs to the branch in curly braces, creating a block.

  • Common mistake

    Assuming the else part runs when the condition is true

    Why it fails

    The statement after else is statement-2, which is taken only when the boolean expression yields false.

    Do this instead

    Read the condition as selecting statement-1 for true and statement-2 for false.

  • Common mistake

    Expecting a statement to run when no else part exists and the condition is false

    Why it fails

    A false result skips statement-1 entirely when there is no else part, and the program continues after the if statement.

Practice Tracing a Branch

EASY

Given int temperature = 18; and the statement if (temperature > 25) System.out.println("Warm"); else System.out.println("Cool");, which line is printed, and which statement is skipped? Explain your answer by naming the boolean expression and its value.

Hints
  • Identify the boolean expression first and decide whether it is true or false for 18.
  • A false result selects the statement after else.
  • Name the skipped statement as statement-1 or statement-2 in your explanation.

Key Takeaways

  • The if statement takes the form if ( boolean-expression ) statement-1 else statement-2, where the boolean expression evaluates to true or false.
  • The if-else is a two-way branch: a true result takes statement-1, and a false result takes statement-2 when an else part exists.
  • The else part is optional. When it is omitted and the expression is false, statement-1 is skipped and the program continues after the if statement.
  • Statements inside an if or else can be blocks written in curly braces, which groups several statements into one branch.
  • To trace an unexpected result, identify the path taken, check the boolean expression's value, and verify that each statement sits in the intended slot.