Java : if Statement


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.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s