If-Else Statement

The if statement is a decision statement.

Example 1. Syntax of the Basic if Statement

if (booleanExpression) {
     System.out.println("In the if block");

Example 2. Syntax of the Basic if-else Statement

if (booleanExpression) {
    System.out.println("Inside if block");
} else {
    System.out.println("Inside else block");

Rules of the if else statement in java:

  • The only legal expression in an if statement is an expression that resolves to a boolean or a Boolean variable.
  • Curly braces are optional for if blocks that have only one conditional statement.
  • It is possible to have zero or one else for a given if, and it must come after any else ifs.
  • It is possible to have zero to many else ifs for a given if and they must come before the (optional) else.
  • Once an else if succeeds, none of the remaining else ifs or elses will be tested.


Sources:  SCJP Sun Certified Programmer for Java 6 Exam 310-065

Leave your comment: