Getting Started
By default, a computer program executes statements sequentially, one after the other, from top to bottom. However, to build powerful and intelligent applications, programs must be able to make decisions and execute different code based on specific conditions. Conditional statements provide this capability, allowing us to control the "flow" of our program's execution.
What You Should Be Able to Do
Explain how an
ifstatement alters the standard sequential flow of program execution.Write a
booleanexpression using relational operators to compare numeric or object values.Implement an
ifstatement to execute a block of code only when a specific condition istrue.Trace the execution of code containing an
ifstatement to determine the final state of variables.
Key Concepts & Java Implementation
The Core Idea
The default path a program takes is called the flow of control. In a simple program, this flow is sequential—like reading a book, you start at the first line and proceed to the next until you reach the end. A conditional statement is a structure that creates a fork in this path. It allows the program to ask a true or false question and, based on the answer, decide whether to execute a specific block of code or to skip it entirely.
The simplest conditional statement in Java is the if statement. It evaluates a boolean expression, which is any expression that results in a value of either true or false. If the expression is true, the code inside the if statement's body is executed. If the expression is false, the program's flow of control skips over that code block and continues with the next statement after it. This gives us the power to make our programs responsive to changing data and user input.
Syntax & Implementation
To form the boolean expressions needed for if statements, we use relational operators. These operators compare two values and produce a boolean result.
Relational Operators Table
| Operator | Meaning | Java Example | Result (x is 10) |
|---|---|---|---|
== | Equal to | x == 10 | true |
!= | Not equal to | x != 5 | true |
> | Greater than | x > 10 | false |
< | Less than | x < 20 | true |
>= | Greater than or equal to | x >= 10 | true |
<= | Less than or equal to | x <= 9 | false |
The if statement uses these expressions to guard a block of code.
General Syntax
if (booleanExpression) {
// This code block runs only if
// booleanExpression evaluates to true.
}
// Program execution continues here, regardless of the condition.
Annotated Java Examples
Basic
ifStatementThis example checks if a student's score qualifies them for an honor roll.
int studentScore = 92; // The boolean expression is (studentScore > 90) if (studentScore > 90) { // This line only executes because 92 > 90 is true. System.out.println("Congratulations on making the honor roll!"); } System.out.println("Processing complete.");Skipping the
ifBlockHere, the condition is
false, so the code inside theifstatement is skipped.int temperature = 65; // The boolean expression (temperature < 32) evaluates to false. if (temperature < 32) { // This code is SKIPPED. System.out.println("Warning: Freezing temperatures detected!"); } // Execution jumps directly to here. System.out.println("Weather report finished.");
Tracing & Analysis
Execution Trace
Tracing code helps us understand how variable values change as the program runs. Let's trace a variable itemsInCart through two different scenarios.
Scenario 1: Condition is true
int itemsInCart = 5;
boolean shippingIsFree = false;
if (itemsInCart > 3) {
shippingIsFree = true;
}
| Line of Code | itemsInCart | shippingIsFree | itemsInCart > 3 | Notes |
|---|---|---|---|---|
int itemsInCart = 5; | 5 | (not yet declared) | Variable initialized. | |
boolean shippingIsFree = false; | 5 | false | Variable initialized. | |
if (itemsInCart > 3) | 5 | false | true | Condition is met. |
shippingIsFree = true; | 5 | true | Code block executes. | |
| End of Snippet | 5 | true | shippingIsFree is now true. |
Scenario 2: Condition is false
int itemsInCart = 2;
boolean shippingIsFree = false;
if (itemsInCart > 3) {
shippingIsFree = true;
}
| Line of Code | itemsInCart | shippingIsFree | itemsInCart > 3 | Notes |
|---|---|---|---|---|
int itemsInCart = 2; | 2 | (not yet declared) | Variable initialized. | |
boolean shippingIsFree = false; | 2 | false | Variable initialized. | |
if (itemsInCart > 3) | 2 | false | false | Condition is not met. |
| End of Snippet | 2 | false | The if block is skipped. shippingIsFree remains false. |
Analysis
The if statement acts as a gatekeeper for the code within its curly braces {}. The program always evaluates the condition inside the parentheses (). Only a true result can "open the gate" and allow the program's flow of control to enter the block. If the result is false, the flow detours around the block, proceeding immediately to the first statement after the closing brace }.
Java Syntax Quick-Reference
if (condition): A keyword that begins a conditional statement. It executes the following code block only ifconditionistrue.boolean: A primitive data type in Java that can only hold the valuestrueorfalse.==: The equality relational operator. Returnstrueif the two operands are equal.!=: The inequality relational operator. Returnstrueif the two operands are not equal.>: The greater than relational operator.<: The less than relational operator.>=: The greater than or equal to relational operator.<=: The less than or equal to relational operator.
Core Code Examples & Terminology
booleanexpression: An expression that evaluates to a final value of eithertrueorfalse. It is used as the condition in control structures.Conditional Statement: A programming construct that allows for the execution of a specific block of code only if a certain condition is met.
Flow of Control: The order in which a program executes its statements. Conditional statements can alter this from a purely sequential flow.
Relational Operators: A set of operators (
==,!=,>,<, etc.) that compare two values and produce abooleanresult.Core Snippet 1: Guarding a print statement
int age = 18; if (age >= 18) { System.out.println("Access granted."); }This code checks if
ageis 18 or greater before printing a message.Core Snippet 2: Modifying a variable conditionally
double balance = 150.0; if (balance < 100.0) { balance += 10.0; // Add a service fee }This code adds a fee to
balanceonly if the balance is below a certain threshold.
Core Skill Check
Code Tracing: What is the final value of
powerLevelafter this Java code runs:int powerLevel = 100; if (powerLevel == 100) { powerLevel = powerLevel + 50; }?- Answer: 150
Debugging: Identify the compile-time error in this Java code:
int x = 10; if (x = 5) { System.out.println("x is 5"); }.- Answer: The condition
(x = 5)uses the assignment operator=instead of the equality operator==. It attempts to assign 5 toxand does not produce abooleanvalue, causing an error.
- Answer: The condition
Application: Write a single line of Java code that starts an
ifstatement to check if aStringvariable namedpasswordis not equal tonull.- Answer:
if (password != null)
- Answer:
Common Misconceptions & Errors
Assignment (
=) vs. Equality (==): A very common mistake is using a single equals sign (=) in a condition. The expressionif (x = 10)attempts to assign 10 tox, it does not comparexto 10. Always use the double equals sign (==) for comparison.Floating-Point Comparisons: Using
==to comparedoubleorfloatvalues can be unreliable due to tiny precision errors in how they are stored. For example,0.1 + 0.2 == 0.3might evaluate tofalse. It is safer to check if the difference between two floating-point numbers is very small.Forgetting Curly Braces
{}: While Java allows you to omit the curly braces for anifstatement that controls only a single line of code, this is considered poor practice. It can easily lead to bugs if you later add another line, forgetting to add the braces. Always use{}to define the body of yourifstatement for clarity and safety.
Summary
Conditional statements are fundamental to programming, allowing applications to perform different actions based on different inputs or states. The if statement is the primary tool for this in Java. It interrupts the normal sequential flow of control by evaluating a boolean expression, often created using relational operators like == or >. If this condition is true, a specific block of code is executed. If the condition is false, that block is skipped, and the program continues on, enabling dynamic and responsive behavior.