The if Statement


It is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not. Here, condition after evaluation will be either true or false.

The if statement accepts Boolean values – if the value is true then it will execute the block of statements under it.
if ( condition ) {
  // Statements to execute
  // if condition is true
}

If we do not provide the curly braces ‘{’ and ‘}’ after if (condition) then by default the if statement will consider the immediate one statement to be inside its block:
if ( condition )
  statement1;
  statement2;

// If the condition is true, the
// if block will consider only
// statement1 to be inside its block.

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error. In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:

 int x = 20;
 int y = 18;
 if ( x > y )  System.out.println( "x is greater than y" );

IfDemo.java (the if statement)
// Java program to illustrate if statement 
class IfDemo { 
  public static void main( String args[ ] ) { 
    if ( args[0] > args[1] )
      System.out.print( args[0] );
    // The above statement will be executed as
    // if considers one statement by default.
    System.out.print( args[1] );
  } 
}
shell> java IfDemo    

Output:           Result:




      A week is a long time in politics.