Java - if-else
Interview Questions of if-else-java
Scenario: Java if-else
Scenario:
Scenario:
You are developing a simple ticket booking system for a movie theater. The system needs to determine the ticket price based on the age of the customer:
Question:
How would you implement this logic using if-else statements in Java? Please write a code snippet and explain your approach.
Answer:
To solve this, I would use an if-else-if ladder to check the customer’s age and assign the correct ticket price:
- If the customer is under 12 years old, the ticket price is ₹100.
- If the customer is between 12 and 60 years old (inclusive), the ticket price is ₹200.
- If the customer is above 60 years old, the ticket price is ₹150.
Question:
How would you implement this logic using if-else statements in Java? Please write a code snippet and explain your approach.
Answer:
To solve this, I would use an if-else-if ladder to check the customer’s age and assign the correct ticket price:
public class TicketBooking { public static void main(String[] args) { int age = 65; // Example 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 first if checks if the age is less than 12 for the child price.
- The else if checks if the age is between 12 and 60 (inclusive) for the standard price.
- The else covers customers above 60 for the senior citizen price.
- This structure ensures only one block runs, based on the customer’s age.