Nested If Else in Java | About, Syntax, Flowchart and Examples
if (condition1) {
// Statements to execute if condition1 is true
if (condition2) {
// Statements to execute if condition1 and condition2 are both true
} else {
// Statements to execute if condition1 is true and condition2 is false
}
} else {
// Statements to execute if condition1 is false
}
Flowchart of Nested If else Statement
Best-suited Java courses for you
Learn Java with these high-rated online courses
Examples of Nested If else in Java
Letβs see some questions on Nested If-else in Java one by one.
Example 1: Movie Ticket Pricing
Problem Statement: Calculate the price of a movie ticket based on the customer's age and whether it's a weekend. The pricing is as follows:
- Children (under 13 years): Rs. 100 on weekdays, Rs. 120 on weekends.
- Adults (13 to 64 years): Rs. 150 on weekdays, Rs. 180 on weekends.
- Seniors (65 years and above): Rs. 130 on weekdays, Rs. 150 on weekends.
public class MovieTicketPricing { public static void main(String[] args) { int age = 30; // Customer's age boolean isWeekend = false; // Is it a weekend?
if (age < 13) { if (isWeekend) { System.out.println("Ticket Price: Rs. 120"); } else { System.out.println("Ticket Price: Rs. 100"); } } else if (age < = 64) { if (isWeekend) { System.out.println("Ticket Price: Rs. 180"); } else { System.out.println("Ticket Price: Rs. 150"); } } else { if (isWeekend) { System.out.println("Ticket Price: Rs. 150"); } else { System.out.println("Ticket Price: Rs. 130"); } } }}
Output
Ticket Price: Rs. 150
The ticket price is determined by the customer's age and whether it's a weekend. A 30-year-old customer on a weekday would pay Rs. 150.
Example 2: Product Category Discount
Problem Statement: Calculate the discount on a product based on its category in a store. The discount rules are:
- Electronics: 10% discount.
- Clothing: 15% discount, but 20% if the purchase amount is over Rs. 5000.
- Food: No discount, unless the purchase amount is over Rs. 1000, then 5% discount.
public class ProductDiscount { public static void main(String[] args) { String category = "Clothing"; // Product category double purchaseAmount = 6000.0; // Purchase amount in Rs.
if ("Electronics".equals(category)) { System.out.println("Discount: 10%"); } else if ("Clothing".equals(category)) { if (purchaseAmount > 5000) { System.out.println("Discount: 20%"); } else { System.out.println("Discount: 15%"); } } else if ("Food".equals(category)) { if (purchaseAmount > 1000) { System.out.println("Discount: 5%"); } else { System.out.println("No Discount"); } } else { System.out.println("No Discount"); } }}
Output
Discount: 20%
The discount is calculated based on product category and purchase amount. For a clothing purchase of Rs. 6000, the discount is 20%.
Explore Online Java Programming Courses
Example 3: Traffic Light Action
Problem Statement: Determine actions based on traffic light colors and the presence of pedestrians. The rules are:
- Green light: "Drive" if no pedestrian is waiting, "Slow down" if a pedestrian is waiting.
- Yellow light: "Prepare to stop", regardless of pedestrians.
- Red light: "Stop", regardless of pedestrians.
public class TrafficLightAction { public static void main(String[] args) { String lightColor = "Green"; // Traffic light color boolean isPedestrianWaiting = true; // Is a pedestrian waiting?
if ("Green".equals(lightColor)) { if (isPedestrianWaiting) { System.out.println("Slow down"); } else { System.out.println("Drive"); } } else if ("Yellow".equals(lightColor)) { System.out.println("Prepare to stop"); } else if ("Red".equals(lightColor)) { System.out.println("Stop"); } }}
Output
Slow down
The program checks the traffic light color and pedestrian status to determine the action. For a green light with a pedestrian waiting, the recommended action is "Slow down".
Key Takeaways
- Nested if-else statements allow for structured and multi-level decision-making processes within a program.
- Each nested if-else condition evaluates a Boolean expression, which must be either true or false to determine the flow of execution.
- Properly structured nested if-else statements can be efficient in terms of execution, as they allow the program to skip unnecessary checks once a true condition is found.
Check out Java Courses Here!
FAQs
What is a nested if-else statement in Java?
A nested if-else statement is an if-else block placed inside another if or else block. It's used to perform a series of condition checks.
How does a nested if-else statement work in Java?
The execution of a nested if-else statement depends on the evaluation of the conditions. The outer if condition is checked first; if it's true, the program then checks the inner if condition. Depending on the outcome of these checks, the appropriate code block is executed.
Can we have multiple levels of nesting in if-else statements?
Yes, you can have multiple levels of nesting in if-else statements in Java. However, excessive nesting can make the code hard to read and maintain. It's generally recommended to avoid deep nesting where possible.
What is the difference between nested if-else statements and else-if ladders?
Nested if-else involves placing an if-else block inside another, while else-if ladders are a chain of if, else if, and else blocks used to execute only one block of code among many based on multiple conditions. Nested if-else is used for more complex decision-making processes.
Are there any best practices for using nested if-else statements in Java?
Yes, some best practices include:
- Avoid deep nesting to maintain code readability.
- Always use proper indentation to make the structure of your code clear.
- Consider using other control structures like switch-case or loops if they can simplify the logic.
- Simplify conditions as much as possible and consider breaking very complex conditions into smaller, more manageable parts.
Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio