- Nested If Statements in Java
- 2. Conditional Statements
- 2.1 Syntax
- 3. Nested If Statements – Code
- 4. Summary
- 5. Download The Source Code
- 12.3. Java – Вложенный оператор if
- Синтаксис
- Пример
- Оглавление
- Nested if Statements in Java
- Syntax of Nested if Statement
- Flowchart
- Working of Nested if Statements in Java
- Examples of Nested if Statements
- Example #1
- Example #2
- Example #3
- Conclusion
- Recommended Articles
Nested If Statements in Java
Java is a popular programming language, created in 1995. It is owned by Oracle, and more than 3 billion devices run Java. It is used for mobile applications (especially Android apps), desktop applications, web servers, and application servers, games, and much more.
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) It is one of the most popular programming language in the world. It is easy to learn and simple to use and is open-source and free. It is secure, fast and powerful and has a huge community support (tens of millions of developers). Java is an object-oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs.
2. Conditional Statements
- the if-else statement , to choose between two alternatives;
- the switch statement , to choose between multiple alternatives.
In this article we will learn how to use if-else conditional statement in java
2.1 Syntax
if (condition) then-statement else else-statement
condition is an expression of type boolean, i.e., a conditional expression that is evaluated to true or false
then-statement is a single statement (also called the then-branch of the if-else statement )
else-statement is a single statement (also called the else-branch of the if-else statement )
First, the condition is evaluated. If the result of the evaluation is the value true, the then-statement is executed, otherwise, the else-statement is executed. In both cases, the execution continues with the statement immediately following the if-else statement.
3. Nested If Statements – Code
In this section we will see examples of nested if statements .
private static void printRange(int value) < if (value < 10) < System.out.println("Value should be greater that 9"); >if (value > 30) < System.out.println("Value should be less than 30"); >if (value >= 15) < if (value > >
4. Summary
In this article we saw how to write a nested if statement in Java. We can write nested else-if statements as well but this article does not cover that.
5. Download The Source Code
This was an example of nested if statements in Java.
12.3. Java – Вложенный оператор if
В Java всегда допустимы вложенные операторы if-else, которые означают, что Вы можете использовать один оператор if или else внутри другого оператора if или else.
Синтаксис
Синтаксис вложенного оператора if..else в Java следующий:
Вы можете делать вложенным else if. else аналогично тому, как мы делали вложенным оператор if в Java.
Пример
Будет получен следующий результат:
Оглавление
- 1. Java – Самоучитель для начинающих
- 2. Java – Обзор языка
- 3. Java – Установка и настройка
- 4. Java – Синтаксис
- 5. Java – Классы и объекты
- 6. Java – Конструкторы
- 7. Java – Типы данных и литералы
- 8. Java – Типы переменных
- 9. Java – Модификаторы
- 10. Java – Операторы
- 11. Java – Циклы и операторы цикла
- 11.1. Java – Цикл while
- 11.2. Java – Цикл for
- 11.3. Java – Улучшенный цикл for
- 11.4. Java – Цикл do..while
- 11.5. Java – Оператор break
- 11.6. Java – Оператор continue
- 12. Java – Операторы принятия решений
- 12.1. Java – Оператор if
- 12.2. Java – Оператор if..else
- 12.3. Java – Вложенный оператор if
- 12.4. Java – Оператор switch..case
- 12.5. Java – Условный оператор (? 🙂
- 13. Java – Числа
- 13.1. Java – Методы byteValue(), shortValue(), intValue(), longValue(), floatValue(), doubleValue()
- 13.2. Java – Метод compareTo()
- 13.3. Java – Метод equals()
- 13.4. Java – Метод valueOf()
- 13.5. Java – Метод toString()
- 13.6. Java – Метод parseInt()
- 13.7. Java – Метод Math.abs()
- 13.8. Java – Метод Math.ceil()
- 13.9. Java – Метод Math.floor()
- 13.10. Java – Метод Math.rint()
- 13.11. Java – Метод Math.round()
- 13.12. Java – Метод Math.min()
- 13.13. Java – Метод Math.max()
- 13.14. Java – Метод Math.exp()
- 13.15. Java – Метод Math.log()
- 13.16. Java – Метод Math.pow()
- 13.17. Java – Метод Math.sqrt()
- 13.18. Java – Метод Math.sin()
- 13.19. Java – Метод Math.cos()
- 13.20. Java – Метод Math.tan()
- 13.21. Java – Метод Math.asin()
- 13.22. Java – Метод Math.acos()
- 13.23. Java – Метод Math.atan()
- 13.24. Java – Метод Math.atan2()
- 13.25. Java – Метод Math.toDegrees()
- 13.26. Java – Метод Math.toRadians()
- 13.27. Java – Метод Math.random()
- 14. Java – Символы
- 14.1. Java – Метод Character.isLetter()
- 14.2. Java – Метод Character.isDigit()
- 14.3. Java – Метод Character.isWhitespace()
- 14.4. Java – Метод Character.isUpperCase()
- 14.5. Java – Метод Character.isLowerCase()
- 14.6. Java – Метод Character.toUpperCase()
- 14.7. Java – Метод Character.toLowerCase()
- 14.8. Java – Метод Character.toString()
- 15. Java – Строки
- 15.1. Java – Метод charAt()
- 15.2. Java – Метод compareTo()
- 15.3. Java – Метод compareToIgnoreCase()
- 15.4. Java – Метод concat()
- 15.5. Java – Метод contentEquals()
- 15.6. Java – Метод copyValueOf()
- 15.7. Java – Метод endsWith()
- 15.8. Java – Метод equals()
- 15.9. Java – Метод equalsIgnoreCase()
- 15.10. Java – Метод getBytes()
- 15.11. Java – Метод getChars()
- 15.12. Java – Метод hashCode()
- 15.13. Java – Метод indexOf()
- 15.14. Java – Метод intern()
- 15.15. Java – Метод lastIndexOf()
- 15.16. Java – Метод length()
- 15.17. Java – Метод matches()
- 15.18. Java – Метод regionMatches()
- 15.19. Java – Метод replace()
- 15.20. Java – Метод replaceAll()
- 15.21. Java – Метод replaceFirst()
- 15.22. Java – Метод split()
- 15.23. Java – Метод startsWith()
- 15.24. Java – Метод subSequence()
- 15.25. Java – Метод substring()
- 15.26. Java – Метод toCharArray()
- 15.27. Java – Метод toLowerCase()
- 15.28. Java – Метод toString()
- 15.29. Java – Метод toUpperCase()
- 15.30. Java – Метод trim()
- 15.31. Java – Метод valueOf()
- 15.32. Java – Классы StringBuilder и StringBuffer
- 15.32.1. Java – Метод append()
- 15.32.2. Java – Метод reverse()
- 15.32.3. Java – Метод delete()
- 15.32.4. Java – Метод insert()
- 15.32.5. Java – Метод replace()
- 16. Java – Массивы
- 17. Java – Дата и время
- 18. Java – Регулярные выражения
- 19. Java – Методы
- 20. Java – Потоки ввода/вывода, файлы и каталоги
- 20.1. Java – Класс ByteArrayInputStream
- 20.2. Java – Класс DataInputStream
- 20.3. Java – Класс ByteArrayOutputStream
- 20.4. Java – Класс DataOutputStream
- 20.5. Java – Класс File
- 20.6. Java – Класс FileReader
- 20.7. Java – Класс FileWriter
- 21. Java – Исключения
- 21.1. Java – Встроенные исключения
- 22. Java – Вложенные и внутренние классы
- 23. Java – Наследование
- 24. Java – Переопределение
- 25. Java – Полиморфизм
- 26. Java – Абстракция
- 27. Java – Инкапсуляция
- 28. Java – Интерфейсы
- 29. Java – Пакеты
- 30. Java – Структуры данных
- 30.1. Java – Интерфейс Enumeration
- 30.2. Java – Класс BitSet
- 30.3. Java – Класс Vector
- 30.4. Java – Класс Stack
- 30.5. Java – Класс Dictionary
- 30.6. Java – Класс Hashtable
- 30.7. Java – Класс Properties
- 31. Java – Коллекции
- 31.1. Java – Интерфейс Collection
- 31.2. Java – Интерфейс List
- 31.3. Java – Интерфейс Set
- 31.4. Java – Интерфейс SortedSet
- 31.5. Java – Интерфейс Map
- 31.6. Java – Интерфейс Map.Entry
- 31.7. Java – Интерфейс SortedMap
- 31.8. Java – Класс LinkedList
- 31.9. Java – Класс ArrayList
- 31.10. Java – Класс HashSet
- 31.11. Java – Класс LinkedHashSet
- 31.12. Java – Класс TreeSet
- 31.13. Java – Класс HashMap
- 31.14. Java – Класс TreeMap
- 31.15. Java – Класс WeakHashMap
- 31.16. Java – Класс LinkedHashMap
- 31.17. Java – Класс IdentityHashMap
- 31.18. Java – Алгоритмы Collection
- 31.19. Java – Iterator и ListIterator
- 31.20. Java – Comparator
- 32. Java – Дженерики
- 33. Java – Сериализация
- 34. Java – Сеть
- 34.1. Java – Обработка URL
- 35. Java – Отправка Email
- 36. Java – Многопоточность
- 36.1. Java – Синхронизация потоков
- 36.2. Java – Межпоточная связь
- 36.3. Java – Взаимная блокировка потоков
- 36.4. Java – Управление потоками
- 37. Java – Основы работы с апплетами
- 38. Java – Javadoc
Nested if Statements in Java
Nested if Statement is one of the decisions making statements in Java that flows according to certain conditions. The branching of these conditions is a result of the program’s state change. That is, there will be an if-else condition inside another if-else. If, if-else, if-else-if, jump, switch-case, etc., are some of the other decision making statements in Java. Now, let us see the Nested-if Statement in detail.
Syntax of Nested if Statement
Following is the syntax of Nested if Statement in Java.
Here, Cond1 is Condition 1, and Cond2 is Condition 2.
Flowchart
The following figure depicts the flow chart of the Nested-if condition.
Working of Nested if Statements in Java
Nested-If works similar to the normal If-else condition. The only difference is that there will be an if condition inside another if condition. The working will be as follows.
- If Condition 1 is True, then go to if condition 2. If condition 2 is satisfied, its body will execute; otherwise, else part will execute.
- If Condition 1 is False, then the body of the else part will be executed.
- Once the condition check is finished, exit the loop.
- Continue the execution of statements after the loop
The count of the if-else condition varies depending on the user’s requirement.
Examples of Nested if Statements
In order to understand Nested-if in detail, let us see the examples using Java.
Example #1
A simple java program to implement Nested-if condition with only if conditions.
//Nested-if Java program with if conditions only public class NestedIfExample < public static void main(String args[]) < //declare 2 variables and store some values in it int num1 = 23; int num2 = 45; //if the number 1 is 23 if( num1 == 23 ) < //if number is 45 if( num2 == 45 ) < System.out.print("Number 1 is :"+ num1 +" and Number 2 is :"+ num2); >// end of if condition 2 > //end of if condition 1 > //end of main method > //end of class
In this program, two variables- num1 and num2 are declared that stores two numbers, 23 and 45, respectively. In the if condition, num1 is checked whether it is 23. As it is true, then nested if gets executed. That is, another if condition, whether number 2 is 45, is also checked. As it is also true, a line is printed, displaying “Number 1 is 23, and Number 2 is 45”.
Example #2
A simple java program to implement Nested-if condition with both if and else conditions.
//Nested-if Java program with both if and else conditions public class NestedIfExample < public static void main(String args[]) < //declare 2 variables and store some values in it int num1 = 23; int num2 = 48; //if the number 1 is 23 if( num1 == 23 ) < //if number is 45 if( num2 == 45 ) < System.out.print("Number 1 is :"+ num1 +" and Number 2 is :"+ num2); >// end of if condition 2 else < System.out.print("Number 2 is not 45"); >//end of else condition 2 > //end of if condition 1 > //end of main method > //end of class
In this program, two variables- num1 and num2 are declared that stores two numbers, 23 and 48, respectively. In the if condition, num1 is checked whether it is 23. As it is true, then nested if gets executed. That is, another if condition, whether number 2 is 45, is also checked. As it is not true, a line gets printed displaying “Number 2 is not 45”.
Example #3
A simple java program to implement a Nested-if condition that takes input from the user.
//Nested-if Java program that takes input from user and checks the condition import java.util.Scanner; public class NestedIfExample < public static void main(String args[]) < //create object of scanner Scanner sc= new Scanner(System.in); System.out.print("Enter the number to be checked: "); int num1 = sc.nextInt(); //if the number 1 is greater than or equal to 23 if( num1 >= 23 ) < System.out.print("Number 1 is :"+ num1 +" and it is greater than 23."); //if number is 45 if( num1 >= 45 ) < System.out.print("Oh!! it is greater than 45 also"); >// end of if condition 2 else < System.out.print(" But, the number "+num1+" is less than 45"); >//end of else condition 2 > //end of if condition 1 else < System.out.print("The number "+num1+" is less than 23"); >//end of else condition 2 > //end of main method > //end of class
In this program, the num1 variable is declared. Then, the user is asked to input num1. Here, 33 is given as input, and In the if condition, num1 is checked whether it is greater than or equal to 23. As it is true, then nested if it gets executed. That is, another if condition, whether number 2 is greater than or equal to 45, is also checked. As it is not true, a line is printed, displaying, “Number 1 is 33, and it is greater than 23. But the number 33 is less than 45”.
Suppose we have given input as 20. What will be the output?? Let us check how the flow will be in that case.
In this case, as the first condition itself is not satisfied, the else part gets executed. That is, a line will be printed as” The number 20 is less than 23”.
Conclusion
Nested if Statement is a decision-making statement in Java containing certain branches with an if condition inside another if condition. Syntax, working, and examples of Nested-if is discussed in this document.
Recommended Articles
This is a guide to Nested if Statements in Java. Here we discuss the Flowchart and Working of Nested if Statements in Java along with the examples and outputs. You may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8