⬅ Previous Topic
Java If StatementNext Topic ⮕
Java if-else-if Statement⬅ Previous Topic
Java If StatementNext Topic ⮕
Java if-else-if StatementIn Java, the if-else
statement lets your program choose between different paths based on conditions. Imagine telling a story: if it rains, you stay home; otherwise, you go out. That’s if-else
in action.
if (condition) {
// Runs if condition is true
} else {
// Runs if condition is false
}
condition
: This is a boolean expression that evaluates to either true or false.condition
evaluates to true
, the code block inside the if
block runs.condition
is false
, the code block inside the else
block runs instead.public class Main {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
}
}
The number is positive.
public class Main {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
}
}
Odd number
Sometimes you want to check another condition only if the first one passes. That’s when nesting helps.
public class Main {
public static void main(String[] args) {
int age = 20;
int score = 85;
if (age >= 18) {
if (score > 80) {
System.out.println("Eligible for scholarship.");
} else {
System.out.println("Eligible, but no scholarship.");
}
} else {
System.out.println("Not eligible.");
}
}
}
Eligible for scholarship.
if
checks a condition and runs code when it’s true.else
provides an alternate path when the if
fails.if-else-if
allows multiple conditions to be checked in order.if
helps for dependent checks.public class Main {
public static void main(String[] args) {
String username = "admin";
String password = "1234";
if (username.equals("admin")) {
if (password.equals("1234")) {
System.out.println("Login successful!");
} else {
System.out.println("Incorrect password.");
}
} else {
System.out.println("Username not found.");
}
}
}
Login successful!
else
block in an if-else
statement in Java?if
statements in Java allow you to check a second condition only if the first one is true.if-else
in Java?int number = 7;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
if
block only executes when the condition evaluates to true
.int age = 20;
int score = 85;
if (age >= 18) {
if (score > 80) {
System.out.println("Eligible for scholarship.");
} else {
System.out.println("Eligible, but no scholarship.");
}
} else {
System.out.println("Not eligible.");
}
What will be the output?⬅ Previous Topic
Java If StatementNext Topic ⮕
Java if-else-if StatementYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.