Conditional Statement:

Conditional Statement checks the condition or compares two values using comparison operators and performs action.
We use if, if-else, else-if statements as conditional statements.


If Statement:

If statement checks a condition and if it is true, it executes the block of code.

if-else.java
public class Main {
    public static void main(String[] args) {
        if (10 > 5) {
            System.out.println("10 > 5");
        } 
    }
}

If-else Statement:

In if else statement, if one condition is true, the respective block of code is executed and all others are ignored. If all conditions are false, code block of else is executed. If-else is used as conditional statement.

if-else.java
public class Main {
    public static void main(String[] args) {
        if (5 > 10) {
            System.out.println("5 > 10");
        } 
        else{
            System.out.println("5 < 10");
        }
    }
}

Else-if Statement:

If you want to check conditions more than one time then use else if. If the condition is true, the respective block of code is executed and all others are ignored.

if-else.java
public class Main {
  public static void main(String[] args) {

    int num1 = 100;
    int num2 = 200;
    int num3 = 300;
    if (num1 > num3 && num1 > num2) {
      System.out.println("num1 > num2 and num3");
    } 
    else if (num2 > num1 && num2 > num3){
      System.out.println("num2 > num1 and num3");
    }
    else{
      System.out.println("num3 > num1 and num2");            
    }
  }
}

Nested if Statement:

When we use one if statement within other if statement, it is called nested if statement.

if-else.java
public class Main {
    public static void main(String[] args) {

        int a = 100, b = 20, c = 30;
        if (a > b) {
            if(a > c){
            System.out.print("a > b and c");
            }
        } 
    }
}

Ternary Operator:

Ternary operator is used as short hand if-else statement. It is also called conditional operator.

if-else.java
public class Main {
    public static void main(String[] args) {

        int a = 10;
        String res = a == 10 ? "a == 10" : "a != 10";
        System.out.println(res);
    }
}


Dangling else Grammar:

If you are using multiple if statements and single else statement, then there is dangling else problem.
if(condition){...}
if(condition){...}
Else{...}
Compiler does not know that with which if, else will go.