Conditional Statements in Java
Conditional Statements in Java
java
CopyEdit
int age = 18;
2. if-else Statement
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;
4. switch Statement
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
java
CopyEdit
int a = 10, b = 20;
🧠 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