Java if else Statement

In this chapter you will learn:

  1. What is Java if else Statement
  2. Syntax for Java if else Statement
  3. Example - 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 w  w  . j a  va 2 s. c  o  m

    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.

Next chapter...

What you will learn in the next chapter:

  1. What is Java if else ladder statement
  2. Syntax for Java if else ladder statement
  3. Example - Java if else ladder statement
Home »
  Java Tutorial »
    Java Langauge »
      Java Statement
Java if Statement
Java if else Statement
Java if else ladder statement
Java nested if statement
Java switch Statement
Java for loop
Java for each loop
Java while Loop
Java do while loop
Java break statement
Java continue statement
Java Comments
Java documentation comment(Javadoc)