A conditional statement allows Java to make a decision based on whether a condition is true or false.
Condition
↓
true / false
↓
Choose which statement to execute
Java's main conditional statements are:
1. if
2. if-else
3. else-if ladder
4. nested if
5. switch
Used when you want to execute code only when a condition is true.
if (condition) {
// statements
}int age = 20;
if (age >= 18) {
System.out.println("Eligible");
}Output:
Eligible
If the condition is false, the body is skipped.
Used when there are two possible paths.
if (condition) {
// true block
} else {
// false block
}int number = 7;
if (number % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}Output:
Odd
true → if block
false → else block
Only one of the two blocks executes.
Used when there are multiple conditions.
if (condition1) {
// block 1
}
else if (condition2) {
// block 2
}
else if (condition3) {
// block 3
}
else {
// default block
}int marks = 75;
if (marks >= 90) {
System.out.println("A");
}
else if (marks >= 75) {
System.out.println("B");
}
else if (marks >= 60) {
System.out.println("C");
}
else {
System.out.println("Fail");
}Output:
B
Java checks from top to bottom.
Once a condition is true, its block executes and the remaining else-if conditions are skipped.
An if statement inside another if statement is called a nested if.
int age = 20;
boolean citizen = true;
if (age >= 18) {
if (citizen) {
System.out.println("Eligible");
}
}Think:
Outer condition
↓
true
↓
Inner condition
↓
true
↓
Execute
Used when one expression needs to be compared against multiple possible values.
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}Output:
Tuesday
Without break, execution can continue into the following cases.
Example:
int x = 1;
switch (x) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
}Output:
One
Two
With:
break;after case 1, execution leaves the switch.
| Statement | Best Used For |
|---|---|
if |
One condition |
if-else |
Two alternatives |
else-if ladder |
Multiple conditions/ranges |
Nested if |
Condition inside another condition |
switch |
Multiple fixed choices |
Need a decision?
↓
┌─────────┴─────────┐
↓ ↓
Conditions Fixed choices
/ranges /known values
↓ ↓
if / else-if switch
if→ "Is this condition true?"
if-else→ "Which of two paths?"
else-if→ "Which condition is true?"
nested
if→ "If this is true, check another condition."
switch→ "Which fixed case matches?"