Java if else Statement

Description

The if statement is a conditional branch statement. We can add else statement to the if statement.

Syntax

Here is the general form of the if-else statement:

 
if (condition) 
   statement1; 
else 
   statement2;

The else clause is optional. Each statement may be a single statement or a compound statement enclosed in curly braces (a block). Only one statement can appear directly after the if or the else. To include more statements, you'll need to create a block, as in this fragment.

Example

 
public class Main {
  public static void main(String[] argv) {
    int i = 1;/*from  w  ww.  jav a  2s .  c om*/

    if (i > 0) {
      System.out.println("Here");
      i -= 1;

    } else
      System.out.println("There");
  }
}
  ]]>

The output:

It is good to include the curly braces when using the if statement, even when there is only one statement in each clause.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures