The if...else Statement


If we want to do something else if the condition is false, we can use the else statement with if statement to execute a block of code when the condition is false.
if ( condition ) {
  // Executes this block if
  // condition is true.
}
else {
  // Executes this block if
  // condition is false.
}

 int time = 20;
 if ( time < 18 )
   System.out.println( "Good day" );
 else
   System.out.println( "Good evening" );
 // Output: Good evening

IfElseDemo.java (the if...else statement)
// Java program to illustrate if-else statement
class IfElseDemo {
  public static void main( String args[ ] ) {
    if ( args[0].equals( args[1] ) )
      System.out.print( 10 );
    else
      System.out.print( args[1] );
  }
}
shell> java IfElseDemo   

Output:           Result:

Short Hand if else (Ternary Operator)
If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

 variable = (condition) ? expressionTrue : expressionFalse;

For example, the previous command can be replaced by the following command:

 int time = 20;
 String result = ( time < 18 ) ? "Good day" : "Good evening";
 System.out.println( result );     // Output: Good evening




      “Knowing others is intelligence;    
      knowing yourself is true wisdom.    
      Mastering others is strength;    
      mastering yourself is true power.”    
      ― Lao Tzu, Tao Te Ching