Java: if-else Statement


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.

 

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