In Java, if-else statements are used to run codes on basis of boolean conditions.
The conditions can be provided in the following ways :
Example :
Suppose if we have an int a whose value is 10. if we provide the boolean condition as "a==10" then it is a true statement. So if the input is :
The output will be :
The conditions can be provided in the following ways :
- if condition
- if-else condition
- if-elseif conditions
- nested if conditions
If Statement :
In if condition a boolean condition is provided after if using "(" and ")".
/*syntax*/ if(booleanCondition){ // program to execute if booleanCondition is true } |
Example :
Suppose if we have an int a whose value is 10. if we provide the boolean condition as "a==10" then it is a true statement. So if the input is :
int a=10; if(a==10){ System.out.println("If part executed!") ; } |
The output will be :
If part executed! |
If-else statement :
In an if-else statement, if the condition of "if" block turns out to be false then else part is executed.
Suppose if the input is :
int a=10; if(a>20){ System.out.println("If part executed!") ; } else {System.out.println("else part executed!") ; } |
The output will be :
else part executed! |
If-elseif statement :
In an if-elseif statement, conditions are provided in the elseif part also. We can combine if-elseif with else also. So when all the conditions will fail else part will execute. Suppose if the input is :
int a=10; if(a>20){ System.out.println("If part executed!") ; } elseif (a>15) {System.out.println("elseif part executed!") ; } else { System.out.println("else part executed!") ; } |
The output will be :
else part executed! |
Nested If statements :
If one "if condition" is provided inside the outer if statement then it is known as nested if statement.
/*syntax*/ if(condition1){ // program executed if condition1 is true if(condition2){ // program executed if condition2 is true } } |
☛ Next >> Switch Statement In Java
The switch statement can be considered as an alternative for if-elseif stat ...
No comments:
Post a Comment