Conditional Statements in Java Explained with Syntax

Conditional Statements in Java

Conditional statements are used to control the flow of execution in a Java program based on certain conditions. They allow the program to make decisions and execute different blocks of code.
Java provides the following conditional statements:
  • if statement
  • if-else statement
  • if-else-if-else statement
  • switch statement
  • Real-Life Examples of Conditional Statements in Java

1. if Statement – Real-Life Example

📌 Example: Checking age for voting
Real life:
If a person’s age is 18 or more, they are eligible to vote.

int age = 20;

if (age >= 18) {
    System.out.println("Eligible to vote");
}

👉 If the condition is true, the message is printed.
👉 If false, nothing happens.

2. if-else Statement – Real-Life Example

📌 Example: Pass or Fail result
Real life:
If marks are greater than or equal to 40, the student passes; otherwise, they fail.

int marks = 35;

if (marks >= 40) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

👉 Only one block executes.

3. if-else-if-else Statement – Real-Life Example

📌 Example: Grade system
Real life:
Grades are assigned based on marks.

int marks = 75;

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");
}

👉 Used when multiple conditions are checked.

4. switch Statement – Real-Life Example

📌 Example: Day of the week
Real life:
Display the day name based on a number.

int day = 3;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    default:
        System.out.println("Invalid day");
}

👉 Best used when checking fixed values.

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know