Java if Statement

Description

Java if statement is used to execute a block of code based on a condition.

Syntax

The following the simplest form of Java if statement:


if(condition) 
   statement;

condition is a boolean expression. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed.

Example

The following code outputs a message based on the value of an integer. It uses the if statement to do the check.


public class Main {
/*w  ww .  j a  v a  2  s .com*/
  public static void main(String args[]) {
    int num = 99;
    if (num < 100) {
      System.out.println("num is less than 100");

    }
  }
}

The output generated by this program is shown here:

Example 2

If statement is often used to to compare two variables. The following code defines two variables, x and y, the it uses the if statement to compare them and prints out messages.


public class Main {
/* w ww. j a  va  2s  .c om*/
  public static void main(String args[]) {
    int x, y;

    x = 10;
    y = 20;

    if (x < y){
      System.out.println("x is less than y");
    }

    x = x * 2;
    if (x == y){
      System.out.println("x now equal to y");
    }

    x = x * 2;
    if (x > y){
      System.out.println("x now greater than y");
    }

    if (x == y){
      System.out.println("===");
    }
  }
}

The output generated by this program is shown here:

Example 3

We can also use a boolean value to control the if statement. The value of a boolean variable is sufficient, by itself, to control the if statement.


public class Main {
  public static void main(String args[]) {
    boolean b;//  w  ww.  j a va  2s . co m
    b = false;
    if (b) {
      System.out.println("This is executed.");
    } else {
      System.out.println("This is NOT executed.");
    }

  }
}

There is no need to write an if statement like this:


if(b == true) ...

The output generated by this program is shown here:





















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