Java From Beginner To Advanced

0% completed

Previous
Next
Java Nested if...else Statement

Nested if...else statements allow you to place one if...else statement inside another. This approach is useful when you need to make decisions based on multiple conditions. When the outcome of the first condition determines the need for further evaluation of another condition, you use nested if...else. This creates a hierarchy or "nesting" of decisions.

Syntax

if (condition1) { // Code block executed when condition1 is true if (condition2) { // Code block executed when condition2 is also true } else { // Code block executed when condition2 is false } } else { // Code block executed when condition1 is false }
  • condition1: The primary condition.
  • condition2: A secondary condition that is evaluated only if condition1 is true.
  • Nested blocks: You can continue nesting further if...else statements as needed.

Example 1: Determining Age Category

Below is an example that uses nested if...else statements to check an individual's age and print a corresponding message.

Java
Java

. . . .

Explanation:

  • Primary Condition: The first if statement checks if age >= 18.
  • Nested Condition: If the person is an adult, a nested if...else checks if the adult's age is 40 or less to further classify the individual.
  • Alternative Path: If the person is not an adult, the else block executes and prints that the person is a minor.

Nested if...else statements enable you to structure multiple levels of conditions for more granular decision making. By understanding and using these structures, you can design programs that handle complex logical conditions cleanly and effectively.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next