Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
If statements in Java
2.1.
Syntax :
2.2.
Java
2.3.
Code Explanation:
3.
What is Nested if Statement in Java?
3.1.
Flowchart Diagram
4.
Working Algorithm of the Nested-If statements
4.1.
Examples
4.2.
Java
4.3.
Code Explanation:
4.4.
Java
4.5.
Code Explanation:
5.
Advantages of Nested If statements in Java
6.
Disadvantages of Nested If statements in Java
7.
Frequently Asked Questions
7.1.
Explain the purpose of using Nested-If statements in Java.
7.2.
What is an example of a nested if condition?
7.3.
How to use two if statements in Java?
7.4.
Is there a limit to nested if statements in Java?
8.
Conclusion
Last Updated: Mar 28, 2024
Medium

Nested If Statements in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

A nested if statement is like a Russian doll of decisions, where one choice leads to another. It's used in programming just like regular ifs, but with added layers. When the condition in the if statement is true, it triggers a specific block of code to run.

nested if statements java

If statements in Java

If statements, also known as conditional statements, are used to execute a specific block of code only if a condition is satisfied. The code block may contain multiple lines or a single line of code. 

Syntax :

if (condition) {
	// statements to be executed
}


For example, In an ongoing offer season, if a person buys items with a total greater than Rs 999, he/she shall have an extra discount of 10% on the total. Check if Mr. Roy is eligible for the seasonal offer and calculate the amount he should pay.

The condition can be framed with the if statement as follows.

if (total>999) {
	seasonalDiscount = 10;
}


Code for the complete Program

  • Java

Java

import java.util.Scanner;
class amount {
public static void main(String[] args) {
// Creation of scanner object
Scanner sc = new Scanner(System.in);

// Taking an integer input from the user for the total generated for the items in the cart
int total = sc.nextInt();

int seasonalDiscount = 0;

// Check if Mr. Roy is eligible for a seasonal discount using the if statement
if (total > 999) {
seasonalDiscount = 10;
}

// Calculation of Total
total = total - (seasonalDiscount * total / 100);

// Print the total calculated
System.out.println(total);
}
}

 

Input:

1000

 

Output:

900

Code Explanation:

The code works as follows:-

  • We first take the total amount from the user and initialize the seasonalDiscount variable with zero.
     
  • Then, using a single if-statement we check if the total exceeds 999 or not. If it does, we set the seasonalDiscount variable to 10.
     
  • After the if-statement, the total is recalculated with the discount. If the discount was 0, the total value remains the same.
     
  • At last, we print the final total to the console.

 

In the next section, we will discuss nested if statements in Java.

Also read, Jump statement in java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Nested if Statement in Java?

When an if block is defined within another if block, it is known as a nested if statement in Java, where the inner block of code is executed only if the condition of the outer if block returns true as well as the condition of the inner if block returns true. 
The nested if statement in Java can be used to check for multiple conditions and execute statements depending on the condition associated with the if block.

Syntax:

if (condition) {
	if (condition) {
		// statements to be executed
	}
}

Flowchart Diagram

Diving deeper, let us look at the flowchart diagram of nested if statements in Java. The flowchart diagram given below explains the working of if statements in Java better.

Flowchart Diagram

Working Algorithm of the Nested-If statements

Now that you have understood the flowchart let us understand the working of Nested-If statements co-relating it with the flowchart given above.

Case 1: The condition for the outer if block is checked first. If it returns true, we move forward to the second condition.

Case 1.1: If the condition of the inner if block also returns true, the code of the inner if block is executed.

Case 1.2: If the condition of the inner if block returns false, the compiler exits the if block, goes to the statements after the if block, and executes them.

Case 2: If the first condition returns false, the compiler exits the if block, goes to the statements after the if block, and executes them.

Examples

In this section we will understand Nested-if statements with a few examples.

Example 1:

Calculate the simple interest of a certain amount provided the conditions: interest rate should be greater than 10%, and the loan term should be less than 5 yrs. 

Complete code of the program is given below.

  • Java

Java

import java.util.Scanner;
class SI {
public static void main(String[] args) {

// Creation of scanner object
Scanner sc = new Scanner(System.in);
int interest = 0;

// Taking an integer input from the user for the principal
int principal = sc.nextInt();

// Taking an integer input from the user for the rate
int rate = sc.nextInt();

// Taking an integer input from the user for the time
int time = sc.nextInt();

// Check if rate>10%
if (rate > 10) {

// Check if time<5 yrs
if (time < 5) {
interest = (principal * rate * time) / 100;

// Print the interest calculated
System.out.println("Simple Interest: " + interest);
}
}
if (interest == 0)
System.out.println("Not eligible for a loan, interest = " + interest);
}
}

 

Input:

12000
15
8

 

Output:

Not eligible for a loan, interest = 0

Code Explanation:

The code performs the following steps to solve the given problem statement:-

  • Initialize the interest variable with 0.
     
  • Input the user's principal value, rate, and time.
     
  • Using the two nested-if statements, we ensure that the interest amount is only computed if the rate is more than 10 percent and the time period is less than 5 years.
     
  • Once the simple interest is computed, it is printed to the console.
     
  • If the code block within the two nested-if statements doesn't run, the interest variable remains 0, indicating that either of the two requirements was not fulfilled.

Example 2

Write a program in Java to calculate the grade of a student.

Conditions are given: if marks> 45, the status is passed

If marks <65 and marks >45, grade C

If marks <85 and marks >65, grade B

If marks <100 and marks >85, grade A

Complete code of the program is given below.

  • Java

Java

import java.util.Scanner;
class Grade {
public static void main(String[] args) {

// Creation of scanner object
Scanner sc = new Scanner(System.in);
String status = "", grade = "";

// Taking an integer input from the user for the marks obtained
int marks = sc.nextInt();

// Check if marks>45
if (marks > 45) {

// marks=<100 and marks >85
status = "Pass";
if (marks <= 100) {
grade = "A";
}

// Check if marks <85 and marks >65
if (marks < 85) {
grade = "B";
}

// Check if marks <65 and marks >45
if (marks < 65) {
grade = "C";
}
} else {
status = "Fail";
grade = "D";
}

// print status and grade
System.out.println("Status: " + status + ", Grade: " + grade);
}
}

 

Input:

78

 

Output:

Status: Passed, Grade: B

 

Code Explanation:

This code takes input from the user and stores it in the marks variable. And then, it uses if-else statements to print the status and grade. The status and grade is found as follows:-

  • If marks are strictly greater than 45, the status variable is set to Passed, and the grade is found using 3 if-statements according to the question.
     
  • For marks smaller than or equal to 45, the status variable is set to Fail, and the grade is set to D.

After the if-else block, the grade and status variable is printed to the console.

In the next section, we will discuss some advantages of the nested if-statements.

Must Read Type Conversion in Java

Advantages of Nested If statements in Java

The advantages of Nested If statements in Java are:

  • Enhanced readability: Nested-if statements can be used to increase code readability. Using nested if, it becomes easier to understand the hierarchy of the conditions met first before execution of the final statement of the innermost if block.
     
  • Reduced Complexity: The complex condition can be divided and implemented using the nested if statements in Java. This reduces the complexity of the code while creating more complex decision-making structures.
     
  • Error handling and debugging: With nested if statements in Java, errors can be managed and corrected more effectively.
     
  • Multiple conditions: Multiple conditions can be checked with nested if statements in Java with reduced complexity.

Disadvantages of Nested If statements in Java

  • Code complexity: The code becomes more complicated and confusing when we have multiple nested if statements. It's like trying to follow a complex series of steps or instructions nested within each other. It becomes challenging to see the order in which things happen. Actions are taken based on those conditions to keep track of the conditions.
     
  • More chances for mistakes: When you have many nested if statements in your code, there is a greater chance of making mistakes that can cause logical errors. It is like keeping track of multiple conditions and ensuring they are in the right place. If you accidentally overlook a condition or put it in the wrong part of the code, it can result in unexpected results or bugs in a program.
     
  • Readability and maintainability: Nested if statements can make the code harder to read and maintain. It becomes difficult to see the overall structure of the code, causing problems when you want to make changes or add new conditions.
     
  • Code duplication: Nested if statements can result in code duplication, where a similar code is repeated multiple times in the if statements. It is like writing the same sentence again and again. This goes against reusing code and can cause problems if you need to change or update the repeated code. 

Frequently Asked Questions

Explain the purpose of using Nested-If statements in Java.

Nested-If statements can be used to check for multiple conditions without increasing the complexity of the code. It instead helps in error handling and enhances readability.

What is an example of a nested if condition?

Imagine checking your age at a movie. There's an outer if statement for age >= 18, and inside that, another if statement to check for student ID for a discount (if age >= 18 and has student ID).

How to use two if statements in Java?

You can use standard if statements one after another, or indent one if statement inside another to create nesting.

Is there a limit to nested if statements in Java?

There's no strict limit, but very deep nesting can make code hard to read. It's generally better to use alternative control structures (like switch statements) for complex logic with many conditions.

Conclusion

In this blog, we have discussed Nested If in Java. Nested if statements in Java act like a decision tree, letting your code handle complex situations. By using them effectively, you can write clear and efficient code that responds to different conditions.

We hope this blog has helped you understand the use of Nested-if statements in Java. We recommend you read our articles on other topics of Java, such as


If you liked our article, do upvote our article and help other ninjas grow. You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

Happy Learning!!

Previous article
Iterable Interface in Java
Next article
Arithmetic Operator
Live masterclass