DEV Community

Anees Abdul
Anees Abdul

Posted on

Conditional Statements in JAVA

What is a Conditional Statement:

-Conditional statements in Java are used to make decisions in a program. They allow the program to execute different blocks of code depending on whether a condition is true or false.

Types of Conditional Statements in Java:

  1. if Statement
  2. if-else Statement
  3. else-if Statement
  4. Nested if Statement

1.1 If Statement:

-This gets executed only when the given condition is true. If the condition is false, then the statement inside the if is completely ignored.

if(condition){
    // code to execute if the condition is true
}
Enter fullscreen mode Exit fullscreen mode
public class IfExample {
    public static void main(String[] args) {

        int number = 10;

        if(number > 0){
            System.out.println("Number is positive");
        }
    }
}

O/P: Number is Positive
Enter fullscreen mode Exit fullscreen mode

2.1 What is If-else Statement:

-This would execute the statement if the condition is false

if(condition){
    // if block
}else{
    // else block
}
Enter fullscreen mode Exit fullscreen mode
public class IfElseExample {
    public static void main(String[] args) {

        int number = -5;

        if(number > 0){
            System.out.println("Positive number");
        }else{
            System.out.println("Negative number");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

3.1: Else if Statement:

  • This statement is used when we need to check multiple conditions.
if(condition1){
    // code
}else if(condition2){
    // code
}else if(condition3){
    // code
}else{
    // default code
}
Enter fullscreen mode Exit fullscreen mode
public class GradeExample {
    public static void main(String[] args) {

        int marks = 85;

        if(marks >= 90){
            System.out.println("Grade A");
        }else if(marks >= 75){
            System.out.println("Grade B");
        }else if(marks >= 50){
            System.out.println("Grade C");
        }else{
            System.out.println("Fail");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

4.1: Nested if Statement:

  • It means if statement inside another if.
public class NestedIfExample {
    public static void main(String[] args) {

        int age = 20;
        boolean hasLicense = true;

        if(age >= 18){
            if(hasLicense){
                System.out.println("You can drive");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)