Last chance! 50% off DataCamp Premium
Sale ends in
The if...else statement in Java is a fundamental control flow construct that allows you to execute certain blocks of code based on specified conditions. It is used to make decisions in your program, enabling different actions based on different inputs or states.
The if...else statement evaluates a boolean expression. If the expression evaluates to true, the code block following the if statement is executed. If it evaluates to false, the code block following the else statement is executed.
if (condition) {
// code block to be executed if condition is true
} else {
// code block to be executed if condition is false
}
condition: A boolean expression that is evaluated by the if statement.else block is optional and executes only if the if condition evaluates to false.if...else Statementpublic class IfElseExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is not positive.");
}
}
}
In this example, the program checks if the number is greater than zero. Since number is 10, which is positive, it prints "The number is positive."
if...else with Multiple Conditionspublic class IfElseMultipleConditions {
public static void main(String[] args) {
int score = 75;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
}
}
This example demonstrates using else if to handle multiple conditions. The program assigns a grade based on the score. Since the score is 75, it prints "Grade: C."
if...else Statementspublic class NestedIfElseExample {
public static void main(String[] args) {
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive.");
} else {
System.out.println("You need a license to drive.");
}
} else {
System.out.println("You are too young to drive.");
}
}
}
In this example, nested if...else statements are used to check both age and possession of a driver's license. The program outputs "You can drive." since the conditions are met.
if...else statements.&&, ||) or breaking logic into separate methods.else if for Multiple Conditions: When you have multiple conditions to check, use else if to avoid unnecessary evaluations and improve performance.{} Usage: Always use braces {} even for single-line blocks. This improves readability and prevents errors during code maintenance.