bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java Tutorial
Java•Java Tutorial

Java 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.

Previous

Java Short Hand If...Else (Ternary Operator)

Next

Java Logical Operators in Conditions

This chapter

Overview
49

Lessons

110m

Read time

1. Java Tutorial2. Java Introduction3. Java Getting Started4. Java Syntax5. Java Statements6. Java Output / Print7. Java Output Numbers8. Java Comments9. Java Variables10. Java Print Variables11. Java Declare Multiple Variables12. Java Identifiers13. Java Constants (final)14. Java Data Types15. Java Numbers16. Java Boolean Data Types17. Java Characters18. Java Data Types Example19. Java Non-Primitive Data Types20. Java var Keyword21. Java Type Casting22. Java Operators23. Java Arithmetic Operators24. Java Assignment Operators25. Java Comparison Operators26. Java Logical Operators27. Java Operator Precedence28. Java Strings29. Java String Concatenation30. Java Numbers and Strings31. Java Special Characters32. Java Math33. Java Booleans34. Java If ... Else35. Java Else36. Java Else If37. Java Short Hand If...Else (Ternary Operator)38. Java Nested If39. Java Logical Operators in Conditions40. Java Switch41. Java While Loop42. Java Do/While Loop43. Java For Loop44. Java Nested Loops45. Java For Each Loop46. Java Break and Continue47. Java Arrays48. Java Arrays Loop49. Java Multi-Dimensional Arrays

On this page

Nested IfReal-Life ExampleNotes