Java Theory
If or Else Conditions
The Java if statement consists a condition, followed by statements. It checks boolean condition true or false. There are various types of if statements in java.
Type of conditional statements:
If Statement
If Statement
If statement is used to check the condition and is followed by a set of statements. The statements to be executed if a condition is true and if the condition is false it won’t execute the block of statements.
Syntax |
---|
if (condition) { Statement //Code to be executed. } |
If-Else Statement
If-Else Statement
The if-else statement is also used to test the conditions. If the condition is true, then if block is executed. If the condition is false, then the else block is executed.
Syntax |
---|
if (condition) { //Code to be executed if condition is true } else { //Code to be executed if condition is false } |
If-Else-If Statement
If-Else-If Statement
The if-else-if statement is used to check the multiple conditions. It is also known as "if else if" ladder. This statement have only one "if" and "else" statements and multiple "else if" statements.
Syntax |
---|
if (condition 1) { //Code to be executed if condition 1 is true } else if (condition 2) { //Code to be executed if condition 2 is true } else if (condition 3) { //Code to be executed if condition 3 is true } else { // Code to be executed if none of the above condition is true } |
Nested If Else Statement
Nested If Statement
The nested if statement means when there is an if statement inside another if statement. The inner if statement to be executes when the condition of outer if statement should be true.
Syntax |
---|
if (condition 1) { //Statement(s) if(condition 2) { //Statement(s) } else { //Statement(s) } } else { //Statement(s) if(condition 3) { //Statement(s) } else { //Statement(s) } } |