DevAcademia
C++C#CPythonJava
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz

Loading Java tutorial…

Loading content
Java BasicsTopic 30 of 59
←PreviousPrevNextNext→

Real-Life Examples of If...Else Statements

Practical Applications of If...Else

If...else statements are used extensively in real-world programming. They allow a program to make decisions by executing different blocks of code based on specific conditions.

User Authentication System

One of the most common uses of if...else statements is in authentication logic. They determine whether login credentials are correct, whether to remember the user, and which dashboard to show based on the user's role.

Example
public class AuthenticationExample {
    public static void main(String[] args) {
        String username = "admin";
        String password = "secret";
        boolean rememberMe = true;

        boolean isAuthenticated = authenticateUser(username, password);

        if (isAuthenticated) {
            System.out.println("Login successful!");

            if (rememberMe) {
                System.out.println("Your login will be remembered for 30 days");
            } else {
                System.out.println("You will be logged out when you close the browser");
            }

            String userRole = getUserRole(username);
            if (userRole.equals("admin")) {
                System.out.println("Welcome, Administrator!");
                showAdminDashboard();
            } else if (userRole.equals("moderator")) {
                System.out.println("Welcome, Moderator!");
                showModeratorDashboard();
            } else {
                System.out.println("Welcome, User!");
                showUserDashboard();
            }
        } else {
            System.out.println("Invalid username or password");

            if (isAccountLocked(username)) {
                System.out.println("Your account has been locked. Contact support.");
            } else {
                int attemptsLeft = getRemainingAttempts(username);
                System.out.println("You have " + attemptsLeft + " attempts left");
            }
        }
    }

    public static boolean authenticateUser(String user, String pass) {
        return user.equals("admin") && pass.equals("secret");
    }

    public static String getUserRole(String username) {
        return "admin";
    }

    public static boolean isAccountLocked(String username) {
        return false;
    }

    public static int getRemainingAttempts(String username) {
        return 2;
    }

    public static void showAdminDashboard() {
        System.out.println("Displaying admin dashboard...");
    }

    public static void showModeratorDashboard() {
        System.out.println("Displaying moderator dashboard...");
    }

    public static void showUserDashboard() {
        System.out.println("Displaying user dashboard...");
    }
}
Output
Login successful!
Your login will be remembered for 30 days
Welcome, Administrator!
Displaying admin dashboard...

E-commerce Discount System

If...else statements are ideal for handling discount rules in e-commerce platforms. They let the program apply different discounts depending on the cart total, user type, holiday season, or coupon codes.

Example
public class DiscountExample {
    public static void main(String[] args) {
        double cartTotal = 250.0;
        String userType = "premium";
        boolean isHolidaySeason = true;
        boolean hasCoupon = true;

        double discount = calculateDiscount(cartTotal, userType, isHolidaySeason, hasCoupon);
        double finalAmount = cartTotal - discount;

        System.out.println("Cart Total: $" + cartTotal);
        System.out.println("Discount: $" + discount);
        System.out.println("Final Amount: $" + finalAmount);
    }

    public static double calculateDiscount(double total, String userType,
                                           boolean isHoliday, boolean hasCoupon) {
        double discount = 0.0;

        if (total > 200) {
            discount += total * 0.1;
        } else if (total > 100) {
            discount += total * 0.05;
        }

        if (userType.equals("premium")) {
            if (total > 150) {
                discount += total * 0.15;
            } else {
                discount += total * 0.1;
            }
        } else if (userType.equals("vip")) {
            discount += total * 0.2;
        }

        if (isHoliday) {
            discount += 15.0;
        }

        if (hasCoupon) {
            double couponDiscount = total * 0.25;
            if (couponDiscount > discount) {
                discount = couponDiscount;
                System.out.println("Using coupon discount");
            }
        }

        double maxDiscount = total * 0.5;
        if (discount > maxDiscount) {
            discount = maxDiscount;
        }

        return discount;
    }
}
Output
Using coupon discount
Cart Total: $250.0
Discount: $125.0
Final Amount: $125.0

Temperature Control System

If...else statements are essential in control systems, such as regulating temperature. They can adjust heating and cooling based on the current temperature, desired temperature, system mode, and whether the room is occupied.

Example
public class TemperatureControl {
    public static void main(String[] args) {
        double currentTemp = 22.5;
        double desiredTemp = 21.0;
        String mode = "auto";
        boolean isOccupied = true;

        controlHVAC(currentTemp, desiredTemp, mode, isOccupied);

        System.out.println("\nTesting edge cases:");
        controlHVAC(30.0, 22.0, "cool", true);
        controlHVAC(15.0, 22.0, "heat", false);
    }

    public static void controlHVAC(double current, double desired, String mode, boolean occupied) {
        System.out.println("\nCurrent: " + current + "°C, Desired: " + desired + "°C");
        System.out.println("Mode: " + mode + ", Occupied: " + occupied);

        double tempDifference = current - desired;

        if (!occupied) {
            System.out.println("Room unoccupied - enabling energy saving mode");
            if (Math.abs(tempDifference) < 3.0) {
                System.out.println("No action needed - within energy saving range");
                return;
            }
        }

        if (mode.equals("heat") || (mode.equals("auto") && tempDifference < 0)) {
            if (tempDifference < -2.0) {
                System.out.println("Turning on HEATING at high power");
            } else if (tempDifference < 0) {
                System.out.println("Turning on HEATING at low power");
            } else {
                System.out.println("No heating needed");
            }
        } else if (mode.equals("cool") || (mode.equals("auto") && tempDifference > 0)) {
            if (tempDifference > 2.0) {
                System.out.println("Turning on COOLING at high power");
            } else if (tempDifference > 0) {
                System.out.println("Turning on COOLING at low power");
            } else {
                System.out.println("No cooling needed");
            }
        } else {
            System.out.println("No action needed - temperature within desired range");
        }

        if (current > 35.0) {
            System.out.println("WARNING: Temperature critically high! Emergency cooling activated.");
        } else if (current < 5.0) {
            System.out.println("WARNING: Temperature critically low! Emergency heating activated.");
        }
    }
}
Output

Current: 22.5°C, Desired: 21.0°C
Mode: auto, Occupied: true
Turning on COOLING at low power

Testing edge cases:

Current: 30.0°C, Desired: 22.0°C
Mode: cool, Occupied: true
Turning on COOLING at high power

Current: 15.0°C, Desired: 22.0°C
Mode: heat, Occupied: false
Room unoccupied - enabling energy saving mode
Turning on HEATING at high power
Test your knowledge: Real-Life Examples of If...Else Statements
Quiz Configuration
4 of 6 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Java BasicsTopic 30 of 59
←PreviousPrevNextNext→