🔀 Conditional Statements in Java
Conditional statements in Java allow your program to make decisions
based on boolean expressions. Depending on whether a condition is
true or false, different blocks of code are executed.
🔹 Types of Conditional Statements
1. if Statement
Executes a block of code if the condition is true.
java
CopyEdit
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
}
2. if-else Statement
Executes one block if the condition is true, another if false.
java
CopyEdit
int number = 5;
if (number % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
3. if-else-if Ladder
Checks multiple conditions in order. The first one that is true gets
executed.
java
CopyEdit
int marks = 75;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
4. switch Statement
Best used when comparing a variable to multiple constant values (like
numbers or strings).
java
CopyEdit
int day = 3;
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");
}
🔸 Use break to prevent "fall-through" (i.e., executing multiple cases in a
row).🔸 switch works with byte, short, int, char, String, and enum
types.
5. Ternary Operator
A shorthand for simple if-else.
java
CopyEdit
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Max is " + max);
🧠 Summary Table
Statement Use Case
if Single condition
if-else Binary decision (true/false)
if-else-if Multiple possible conditions
Multiple exact matches (e.g.,
switch
enums, days)
Ternary ?: Simple one-line decisions