Java - Statement if Statement

Syntax

The format of an if-else statement is

if (condition)
    statement1
else
    statement2

The condition must be a Boolean expression, which evaluates to true or false.

If the condition evaluates to true, statement1 is executed. Otherwise, statement2 is executed.

The else part is optional. You may write a statement as


if (condition)
    statement1

Example

The following code checks the num1 value range.

int num1 = 20;
int num2 = 30;
if (num1 > 50)
   num2 = num2 + 10;
else
   num2 = num2 - 10;

Demo

public class Main {
  public static void main(String[] args) {
    int num1 = 20;
    int num2 = 30;
    if (num1 > 50)
      num2 = num2 + 10;//  w  w w  .  java 2 s .  co  m
    else
      num2 = num2 - 10;
    System.out.println("num2 = " + num2);

  }
}

Result

if block statement

You can bundle two statements into one block statement.

if (num1 > 50) {
  num2 = num2 + 10;
  num3 = num3 + 10;
} else {
  num2 = num2 - 10;
  num3 = num3 - 10;
}

Demo

public class Main {
  public static void main(String[] args) {
    int num1 = 20;
    int num2 = 30;
    int num3 = 40;
    if (num1 > 50) {
      num2 = num2 + 10;//from www  .j  av  a  2s. com
      num3 = num3 + 10;
    } else {
      num2 = num2 - 10;
      num3 = num3 - 10;
    }
    System.out.println("num2 = " + num2);
    System.out.println("num2 = " + num3);
  }
}

Result

Related Topics

Quiz

Exercise