If-Else Statements
Conditional statements let your program make decisions. The if-else statement checks a condition and executes different code blocks depending on whether the condition is true or false. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
How If-Else Works
The if statement evaluates a boolean condition. If the condition is true, the code inside the if block runs. If it's false, the code inside the else block runs (if provided). You can chain multiple conditions with 'else if' for more complex decision-making.
If-Else Examples
public class IfElseDemo {
public static void main(String[] args) {
int age = 20;
// Simple if-else
if (age >= 18) {
System.out.println("You are an adult!");
} else {
System.out.println("You are a minor.");
}
// If-else if-else chain
int score = 85;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
System.out.println("Score: " + score + " → Grade: " + grade);
// Nested if
boolean hasTicket = true;
int personAge = 15;
if (hasTicket) {
if (personAge >= 13) {
System.out.println("Welcome to the movie!");
} else {
System.out.println("You need a parent.");
}
} else {
System.out.println("Please buy a ticket first.");
}
// Ternary operator (shorthand if-else)
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println("Status: " + status);
}
}