Conditional statements allow your program to branch out. Think of it like a flow chart.
If it is raining, then take an umbrella.
Else, if it is sunny, then wear sunglasses.
Else, just walk normally.
In Java, we primarily use if, else if, else, and switch.
The 3 Main Types of Logic Gates
1. The if and else blocks
This is the most common way to control flow. It checks a condition (which must be true or false).
if (condition): Runs the code inside{}only if the condition is true.else if (anotherCondition): Checked only if the firstifwas false.else: The "safety net." It runs if none of the above conditions were met.
2. The Ternary Operator (The Shortcut)
If you have a very simple if-else that just assigns a value, you can do it in one line: variable = (condition) ? valueIfTrue : valueIfFalse;
3. The switch Statement (The Multi-Choice)
If you are checking a single variable against many specific values (like a menu or days of the week), switch is much cleaner than writing ten else if statements.
The Code Example:
public class ConditionalsDemo {
public static void main(String[] args) {
int examScore = 85;
char grade;
// --- 1. Using If-Else If-Else ---
if (examScore >= 90) {
grade = 'A';
} else if (examScore >= 80) {
grade = 'B';
} else if (examScore >= 70) {
grade = 'C';
} else {
grade = 'F';
}
System.out.println("With a score of " + examScore + ", your grade is: " + grade);
// --- 2. Using a Switch Statement ---
int dayOfWeek = 3; // Let's say 1=Mon, 2=Tue, 3=Wed...
String dayName;
switch (dayOfWeek) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
default: dayName = "Weekend!"; break;
}
System.out.println("Today is: " + dayName);
// --- 3. The Ternary Operator ---
int age = 19;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println("User Status: " + status);
}
}Expected Output:
With a score of 85, your grade is: B
Today is: Wednesday
User Status: AdultConditionals turn a "script" into an "application." Every time you see a "Premium Member" feature locked on a website, or a game character dies when health hits zero, there is an if statement behind the scenes checking that logic.
Note on
break: In theswitchstatement, always remember thebreak;keyword. If you forget it, Java will "fall through" and execute all the code in the cases below it!