DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Conditional Statement - if-else Statement

Conditional Statement/Decision making Statement/Control Flow Statement - if-else Statement :

  • The if-else statement is used to make decisions in a program based on a boolean condition.
  • It executes the code block only if the condition is true.

Core Conditional Statements :

if Statement: The most basic form. It executes a block of code only if the specified condition is true.

if (age >= 18) {
System.out.println("You are an adult.");
}

if-else Statement: Provides an alternative path. If the if condition is false, the else block executes.

if (marks >= 35) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}

else-if Ladder: Used to check multiple conditions. Once a true condition is found, its block runs, and the rest of the ladder is skipped.

if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 35) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}

Core Rules :

Boolean Condition Required: The condition within the if statement parentheses () must be a boolean expression. We cannot use an integer or other non-boolean values as conditions in Java.
else is Optional: An if statement can exist alone without an else block.
Curly Braces {}: If the if or else block contains more than one statement, we must enclose them within curly braces {}.
Execution Flow: In an if-else-if ladder, conditions are evaluated from top to bottom. As soon as a condition evaluates to true, its corresponding block of code is executed, and the rest of the conditions in the ladder are skipped.

Top comments (0)