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 

Using 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;
    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:


This is NOT executed.
Home 
  Java Book 
    Language Basics  

Statement:
  1. Simplest if statement
  2. If else statement
  3. switch statement
  4. while loop
  5. do-while statement
  6. for Loop
  7. for each loop
  8. break to Exit a Loop
  9. continue
  10. return statement returns from a method.
  11. Comments