The if-else statement is the decision-making statement, Use with conditional expression execution result is true then only the block associated with if statement will execute otherwise control will reach to else block.
Syntax:
if(test_expression) { //execute your code } else { //execute your code }
Note :
In if-else statement else is an optional clause. Below is the format without the else clause:
if (test-expression) { statement }
See Also :
if-else Statement Example
public class IfElseStatementTest{ public static void main(String args[]){ int a=20; if(a>0){ System.out.println("a is positive number"); } else{ System.out.println("a is negative number or zero"); } }
Output
a is positive number
Note :
The if-else statement can be a simple statement terminated by a semicolon or a block enclosed in curly braces.
For Example: Below code is equivalent to same as above example and return same result.
public class IfStatementTest{ public static void main(String args[]){ int a=20; if(a>0) System.out.println("a is positive number"); else System.out.println("a is negative number or zero"); }
Recommendation :
- For better understanding of code always use curly braces ({}) with if , if-else-if or if-else statements.
- It always create confusion when more than one statement are in code.
You must log in to post a comment.