Java If … Else

Java If … Else

if and else statements are used in Java to make decisions based on conditions. They allow the program to execute different blocks of code depending on whether a condition is true or false.


Basic Syntax

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

🧠 Example

int age = 18;

if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}


🔹 if Statement Only

Sometimes you may only need an if without else:

int number = 10;

if (number > 0) {
System.out.println("Positive Number");
}


🔹 if ... else if ... else

Used when there are multiple conditions to check.

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");
}


🔹 Nested if (if inside another if)

int age = 25;
boolean hasID = true;

if (age >= 18) {
if (hasID) {
System.out.println("You can enter.");
} else {
System.out.println("ID required.");
}
} else {
System.out.println("You are too young.");
}


🔹 Short If (Ternary Operator)

A shorter way to write an if-else statement.

int number = 10;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(result);

⭐ Full Example

public class Main {
public static void main(String[] args) {

int temperature = 30;

if (temperature > 35) {
System.out.println("It's very hot!");
} else if (temperature > 20) {
System.out.println("Weather is pleasant.");
} else if (temperature > 10) {
System.out.println("It's cold.");
} else {
System.out.println("Very cold weather.");
}
}
}


📌 Summary

Structure Use Case
if Executes only when condition is true
if...else Runs one of two code blocks
else if Multiple conditions
Nested if Decision inside another decision
Ternary ?: Short version of if/else

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 *