Loading

Q1. How can conditional logic be implemented in Java using if-esle statements ?
Conditional logic in Java can be implemented using an if-else-if ladder, which allows the program to execute different blocks of code based on given conditions.

This structure is useful when multiple mutually exclusive conditions need to be evaluated, and only one block should execute.

Example: Ticket Price Calculation Using if-else
public class TicketBooking {

    public static void main(String[] args) {

        int age = 65; // Customer age
        int ticketPrice;

        if (age < 12) {
            ticketPrice = 100;
        }
        else if (age <= 60) {
            ticketPrice = 200;
        }
        else {
            ticketPrice = 150;
        }

        System.out.println("Customer age: " + age);
        System.out.println("Ticket price: ₹" + ticketPrice);
    }
}


Explanation

  • The if condition checks whether the customer is a child (under 12 years).
  • The else if condition checks whether the customer falls within the adult age range (12 to 60 years).
  • The else block handles senior citizens (above 60 years).
  • Only one condition is executed because if-else follows a top-down evaluation.

Why if-else is Suitable Here

  • Improves readability for decision-based logic
  • Ensures exclusive execution of conditions
  • Easy to maintain and modify