Java If…Else Examples

Java If…Else Examples

if, else if, and else statements allow your Java program to make decisions based on conditions.


1️⃣ Basic if Statement

Runs a block of code only if the condition is true.


 

📌 Output:

You are an adult.

2️⃣ if...else Example

Executes one block if the condition is true, otherwise executes another.


 

📌 Output:

Not eligible to vote.

3️⃣ if...else if...else Example

Used when there are multiple conditions.


 

📌 Output:

Grade: A

4️⃣ Nested if Statement

if inside another if.


 

📌 Output:

You are allowed to drive.

5️⃣ Ternary Operator (Shortcut for if…else)

A shorter way to write simple conditions.


 

📌 Output:

Even

🧠 Summary

StructureUse Case
ifOne condition
if...elseTwo possible outcomes
else ifMultiple conditions
Nested ifCondition inside another
Ternary (? :)Short form decision

You may also like...