Simplest if statement

Java has two selection statements: if and switch. Simplest if statement form is shown here:


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.

Here is an example:


public class Main {

  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:


num is less than 100

Using if statement to compare two variables


public class Main {

  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:


x is less than y 
x now equal to y 
x now greater than y 
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.