* In Java, if and else statements are fundamental control flow constructs used for decision-making. They allow a program to execute different blocks of code based on whether a specified condition evaluates to true or false.
- The if statement:
- The if statement executes a block of code only if its condition is true SYNTAX
if (condition) {
// Code to be executed if the condition is true
}
Working of if Statement
- The if-else statement:
- The if-else statement provides an alternative block of code to execute if the if condition is false. SYNTAX
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
- The else if statement (for multiple conditions):
- When there are multiple conditions to check sequentially, else if can be used after an if statement. The first true condition's block will be executed, and the rest will be skipped. SYNTAX
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2 (if condition1 is false)
} else {
// Code if none of the above conditions are true
}
Key Points:
- Condition:
- The condition inside the parentheses must be a Boolean expression (evaluates to true or false).
- Curly Braces:
- The code blocks associated with if, else if, and else are enclosed in curly braces {}.
- Optional else:
- The else block is optional; an if statement can exist without a corresponding else.
- Execution Flow:
- Only one block of code within an if-else if-else chain will be executed. The first true condition determines which block runs
REFERRED LINKS
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.