Java if Statement
Table of Contents + −
In the last lesson you learned about Java command-line arguments. Real programs make choices, and to make a choice Java uses the if statement. Let’s learn the most important building block of logic.
🤔 Why do we need if?
Without if, a program does the same thing every run. Think about an ATM. It does not hand out cash blindly. It decides first.
- It gives you cash only if your balance is enough.
- It shows an error only if the PIN is wrong.
- It blocks the card only if you fail too many times.
Those “only if” parts are decisions.
- An
ifruns a block only when its condition is true. - If the condition is false, that block is skipped.
- Every useful program is full of these forks, and each one is an
if.
🧩 The if syntax
The basic shape: the keyword if, a condition in round brackets, then a block in curly braces.
if (condition) { // this code runs only if the condition is true}Each piece has a job:
ifis the keyword that tells Java “a decision is coming”.(condition)is the test inside parentheses. It must betrueorfalse.{ ... }is the body, the code that runs when the condition is true.
The condition must be a boolean.
- If it is
true, Java runs the braces. - If it is
false, Java skips the block and moves to the next line.
This program checks if a number is positive.
int number = 5;if (number > 0) { System.out.println("The number is positive");}numberis 5, sonumber > 0istrue, and the message prints.- If
numberwere-3, the test would befalseand nothing would print.
Output
The number is positiveThe same code can print or stay silent. The value decides. That is the whole point of if.
🎯 A real decision: the age gate
Many sites check your age before letting you in. That is an age gate. This checks if someone is old enough to vote.
int age = 20;if (age >= 18) { System.out.println("You are eligible to vote");}>=means “greater than or equal to”.- With
ageof 20,20 >= 18istrue, so the message prints. - With
ageof 16,16 >= 18isfalse, so nothing prints.
Output
You are eligible to voteYou did not change the code. You changed the data, and the behaviour changed with it. That is why if matters.
🔍 Where conditions come from
A condition is always a value that works out to true or false. It usually comes from two kinds of operators.
- Comparison operators:
==(equal),!=(not equal),>,<,>=,<=. - Logical operators:
&&(and),||(or),!(not).
You can also store the result in a boolean variable first, then test that variable. It reads like a sentence.
int passwordLength = 6;boolean isLongEnough = passwordLength >= 8;if (isLongEnough) { System.out.println("Password length is fine");}passwordLength >= 8isfalse, because 6 is not at least 8.- So
isLongEnoughholdsfalse, the block is skipped, and nothing prints. - This is the real check websites use to refuse a too-short password.
🔗 if with combined conditions
You can join checks with logical operators. This lets a user in only if they are an adult and have a ticket.
int age = 25;boolean hasTicket = true;if (age >= 18 && hasTicket) { System.out.println("Welcome to the show");}&&means both parts must be true at the same time.- Here both are true, so the block runs.
- If either part were false, the whole condition would be false and the block would be skipped.
- Use
||instead when only one part needs to be true, like free shipping for a large order or a member.
Output
Welcome to the showThe condition must be a boolean
Whatever you put in the if parentheses has to be a true or false value. A comparison like age >= 18 gives a boolean, so that is fine. But a plain number like if (age) does not work in Java, unlike some other languages. So always give if a real boolean condition.
📦 Why the curly braces matter
The braces mark exactly which code belongs to the if. Code inside runs only when the condition is true. Code after the closing brace runs no matter what.
int score = 30;if (score >= 40) { System.out.println("You passed");}System.out.println("Thanks for playing");- The first message is inside the braces, so it is skipped when
scoreis 30. - The second message is outside, so it always runs.
Output
Thanks for playingJava lets you skip the braces when the if controls just one line. That is legal, but it sets a trap. Watch what happens when you add a second line.
int score = 30;if (score >= 40) System.out.println("You passed"); System.out.println("Here is your prize"); // ❌ NOT controlled by the if- Without braces, only the very first line after the
ifis controlled. - The indentation makes both lines look grouped, but the second runs every time.
- So the prize prints even when the score is 30 and the student failed. This is the dangling-statement bug.
Output
Here is your prizeThe fix is simple. Always wrap the body in braces.
int score = 30;if (score >= 40) { System.out.println("You passed"); System.out.println("Here is your prize"); // ✅ now clearly inside the if}Now both lines are inside, so both are skipped when the score is 30. The braces made the grouping certain.
🪆 Nesting ifs
Putting an if inside another if is called nesting. The inner check runs only if the outer check already passed. Use it when a second decision only makes sense after the first is true.
boolean userExists = true;String password = "secret123";if (userExists) { if (password.equals("secret123")) { System.out.println("Login successful"); }}- The outer
ifchecksuserExists, which is true, so Java steps inside. - The inner
ifchecks the password with.equals(...), the correct way to compare text in Java. - The password matches, so “Login successful” prints.
- If
userExistswere false, Java would never look at the password.
Output
Login successfulKeep nesting shallow. Two levels are usually fine. Beyond that, join the tests with && instead, or split the work into smaller methods later.
⚠️ Common Mistakes
A few if slip-ups catch almost everyone. Spot them now and save yourself hours.
Using = instead of ==:
// ❌ Avoid: = assigns, it does not compare// if (score = 100) ...
// ✅ Good: == comparesif (score == 100) { System.out.println("Perfect");}=assigns a value;==compares two values.- With two
intvalues, Java rejects=inside anifas a type error. - But with
booleanvariables this mistake can compile and silently misbehave, so train your fingers to type==.
Putting a semicolon right after the if:
// ❌ Avoid: the ; ends the if, so the block always runs// if (age >= 18); { System.out.println("Adult"); }
// ✅ Good: no semicolon after the conditionif (age >= 18) { System.out.println("Adult");}- The
;ends theifearly, so it controls an empty statement. - Then your block runs no matter what, even for a 10-year-old.
- Go straight from the closing
)to the opening{.
Forgetting braces for more than one line:
// ❌ Avoid: only the first line is inside the if// if (loggedIn)// showDashboard();// loadUserData(); // runs even when loggedIn is false
// ✅ Good: braces group both lines togetherif (loggedIn) { showDashboard(); loadUserData();}- This is the dangling-statement bug again. Without braces, only the very next line belongs to the
if.
✅ Best Practices
Habits that keep your conditions clean and bug-free:
- Always use braces, even for a single line. They stop the dangling-statement bug.
- Give the
ifa real boolean, usually through a comparison. - Use
==to compare, never=. - Never put a semicolon after the condition. Go straight from
)to{. - Keep conditions readable. One clear comparison, or a couple joined with
&&or||. - Compare text with
.equals(...), not==. ForStringvalues,==checks the wrong thing. - Keep nesting shallow. Two levels are fine; beyond that, join tests with
&&.
🧩 What You’ve Learned
Great, your programs can decide now. Let’s recap.
- ✅ The if statement runs a block of code only when its condition is true, and skips it otherwise.
- ✅ The condition in the parentheses must be a boolean, usually from a comparison or a logical operator.
- ✅ The curly braces mark exactly which code the
ifcontrols, and skipping them causes the dangling-statement bug. - ✅ You can combine checks with
&&and||, and you can nest oneifinside another. - ✅ Use
==to compare (not=), and never put a semicolon right after the condition.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
When does the code inside an if block run?
Why: The if block runs only when its condition evaluates to true. Otherwise it is skipped.
- 2
What kind of value must an if condition be?
Why: An if condition must be a boolean. A comparison like age >= 18 gives one.
- 3
What is wrong with: if (score = 100) { ... }
Why: A single = assigns a value. To compare, you need ==, so it should be if (score == 100).
- 4
What does a semicolon right after if (age >= 18); do?
Why: The semicolon ends the if statement immediately, so the following block always runs. Remove it.
🚀 What’s Next?
An if runs code when something is true. But often you also want a backup plan for when it is false. “Pass, otherwise Fail.” That is what if-else is for. Let’s learn it next.