Java If
Java If
Introduction
In Java, control flow statements are used to manage the flow of execution based on certain
conditions. Among these, the if, if-else, nested if, and if-else-if statements are fundamental for
making decisions in code. These statements allow the program to choose different paths of
execution based on the evaluation of boolean expressions.
Table of Contents
o If Statement
o If-Else Statement
o Nested If Statement
o If-Else-If Statement
Control flow statements in Java determine the order in which statements are executed. These
statements enable the program to make decisions, repeat tasks, and branch into different
execution paths. The if, if-else, nested if, and if-else-if statements are used to evaluate
conditions and execute specific blocks of code based on whether the conditions are true or
false.
1. If Statement
2. If-Else Statement
3. Nested If Statement
4. If-Else-If Statement
1. If Statement
The if statement is used to test a condition. If the condition evaluates to true, the block of code
inside the if statement is executed.
Syntax:
if (condition) {
Example:
if (num > 0) {
2. If-Else Statement
The if-else statement is used to execute one block of code if the condition is true and another
block of code if the condition is false.
Syntax:
if (condition) {
} else {
Example:
if (num > 0) {
} else {
3. Nested If Statement
A nested if statement is an if statement inside another if statement. This allows for more
complex conditions to be tested.
Syntax:
if (condition1) {
if (condition2) {
Example:
int num = 5;
if (num > 0) {
if (num < 10) {
4. If-Else-If Statement
The if-else-if statement is used to test multiple conditions. It executes a block of code
corresponding to the first true condition. If none of the conditions is true, the else block is
executed.
Syntax:
if (condition1) {
} else if (condition2) {
} else {
Example:
int num = 0;
if (num > 0) {
} else {