🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Java Notes
Topic #40

Nested If


Nested If

You can also place an if statement inside another if. This is called a nested if statement.

A nested if lets you check for a condition only if another condition is already true.

Syntax

if (condition1) {
  // code to run if condition1 is true
  if (condition2) {
    // code to run if both condition1 and condition2 are true
  }
}

Example

In this example, we first check if x is greater than 10. If it is, we then check if y is greater than 20:

Example

int x = 15;
int y = 25;

if (x > 10) {
  System.out.println("x is greater than 10");

  // Nested if
  if (y > 20) {
    System.out.println("y is also greater than 20");
  }
}

Real-Life Example

Nested if statements are useful when you need to test multiple conditions that depend on each other. For example, checking if a person is old enough to vote, and if they are a citizen:

Example

int age = 20;
boolean isCitizen = true;

if (age >= 18) {
  System.out.println("Old enough to vote.");

  if (isCitizen) {
    System.out.println("And you are a citizen, so you can vote!");
  } else {
    System.out.println("But you must be a citizen to vote.");
  }
} else {
  System.out.println("Not old enough to vote.");
}

Notes

  • You can nest as many if statements as you want, but avoid making the code too deep - it can become hard to read.
  • Nested if is often used together with else and else if for more complex decision making.

Want to go beyond the notes?

Join CodingNow 2.0's Java course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Nested If – FAQs

Quick answers about learning Nested If in Java.

This free note from CodingNow 2.0 explains Nested If in Java — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Java topic on CodingNow 2.0, including Nested If, is 100% free with no signup required.
With focused practice, most students grasp Nested If in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now