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.

public class Main {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println(“You are an adult.”);
}
}
}

📌 Output:

You are an adult.

2️⃣ if...else Example

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

public class Main {
public static void main(String[] args) {
int age = 15;
if (age >= 18) {
System.out.println(“Eligible to vote.”);
} else {
System.out.println(“Not eligible to vote.”);
}
}
}

📌 Output:

Not eligible to vote.

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

Used when there are multiple conditions.

public class Main {
public static void main(String[] args) {
int marks = 75;
if (marks >= 90) {
System.out.println(“Grade: A+”);
} else if (marks >= 75) {
System.out.println(“Grade: A”);
} else if (marks >= 50) {
System.out.println(“Grade: B”);
} else {
System.out.println(“Fail”);
}
}
}

📌 Output:

Grade: A

4️⃣ Nested if Statement

if inside another if.

public class Main {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println(“You are allowed to drive.”);
} else {
System.out.println(“You need a driving license.”);
}
} else {
System.out.println(“You are too young to drive.”);
}
}
}

📌 Output:

You are allowed to drive.

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

A shorter way to write simple conditions.

public class Main {
public static void main(String[] args) {
int number = 10;
String result = (number % 2 == 0) ? “Even” : “Odd”;

System.out.println(result);
}
}

📌 Output:

Even

🧠 Summary

Structure Use Case
if One condition
if...else Two possible outcomes
else if Multiple conditions
Nested if Condition inside another
Ternary (? :) Short form decision

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *