The if-statement is a decision-making statement, used to control the program flow based on some conditional statements. If the execution result of the statement is true then only the block associated with if-statement will execute otherwise skipped. This if-statement is the simplest way to modify the control execution flow of the program.
Syntax:
if(test_expression) { statement 1; statement 2; ... }
See Also :
if Statement Example
public class IfStatementTest{ public static void main(String args[]){ int a=20; if(a>0){ System.out.println("a is positive number"); } if(a<0){ System.out.println("a is negative number"); } }
Output
a is positive number
Note :
The if statement can be a simple statement terminated by a semicolon or a block enclosed in curly braces.
For Example, the Below code is equivalent to the same as the above example and return the same result.
public class IfStatementTest{ public static void main(String args[]){ int a=20; if(a>0) System.out.println("a is positive number"); if(a<0) System.out.println("a is negative number"); }
Recommendation :
- For better undesirability of code always use curly braces ({}) with if, if-else-if or if-else statements.
- It always creates confusion when more than one statement is in code.
You must log in to post a comment.