Java If-Else
What is if-else?
In Java, the if-else statement helps your program make decisions. It checks if a condition is true or false, and then decides what to do next.
Basic Structure
if (condition) {
// runs if the condition is true
} else {
// runs if the condition is false
}Example
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is not positive.");
}The number is positive.
if – else if – else (Multiple Choices)
When you have more than one condition, use else if.
int marks = 82;
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 75) {
System.out.println("Grade: B");
} else if (marks >= 60) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}Grade: B
Nested if (if inside another if)
You can also put one if inside another — this is called a nested if.
int age = 20;
boolean hasID = true;
if (age >= 18) {
if (hasID) {
System.out.println("You can enter the club.");
} else {
System.out.println("You need an ID to enter.");
}
} else {
System.out.println("You are too young to enter.");
}You can enter the club.
Ternary Operator – Short Form
The ternary operator is a shortcut for simple if-else statements.
int num = -5; String result = (num > 0) ? "Positive" : "Negative or Zero"; System.out.println(result);
Negative or Zero
Common Mistakes to Avoid
Mistake | Correct |
if x > 5 | if (x > 5) |
if (x = 5) (assigns value) | if (x == 5) (compares value) |
Forgetting curly braces {} | Always use {} for clarity |
Practice Time!
Check if a number is even or odd.
Check if someone can vote (age ≥ 18).
Find the largest of two numbers.
Check if a year is a leap year.
Create a simple grading system based on marks.
Summary
Keyword | Meaning |
if | Checks a condition |
else if | Adds another condition to check |
else | Runs if none of the above are true |
? : | Ternary operator (short if-else) |