Java if else statement is decision making statements. It checks one or more conditions in program.
Java has the following four conditional statements.
- if statement - An if statement consists of a boolean expression followed by one or more statements.
- if...else statement - An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
- nested if statement - We can use one if or else if statement inside another if or else if statement(s).
- switch statement - We can use switch statement to specify many alternative blocks of code to be executed.
if Statement
We can use if statement to specify a block of code to be executed, if a specified condition is true
Syntax :
if (condition) {
// block of code to be executed if the condition is true
}
if...else statement
We can use else statement to specify a block of code to be executed, if the same condition is false
Syntax :
if (condition) {
// A block of code to be executed if the condition is true.
} else {
// A block of code to be executed if the condition is false.
}
else if statement
We can use the else if statement to specify a new condition if the first condition is false.
Syntax :
if (condition1) {
// block of code to be executed if condition1 is true,
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true.
} else {
// block of code to be executed if the condition1 is false and condition2 is false.
}
Using if else staments, we can check usual logical conditions from mathematics as below.
- Less than: p < q
- Less than or equal to: p <= q
- Greater than: p > q
- Greater than or equal to: p >= q
- Equal to p == q
- Not Equal to: p != q
Comments