Summary: In this tutorial, you will learn about if and if-else control flow statement in Java with the help of examples.
If Statement
In Java, if
and else
are control statements that allow you to specify conditions under which a certain block of code should be executed.
Here is an example of an if
statement in Java:
if (condition) {
// code block to be executed if condition is true
}
The condition
in the if
statement is a boolean expression that evaluates to either true
or false
. If the condition is true
, the code block inside the curly braces will be executed. If the condition is false
, the code block will be skipped.
Here is an example of an if
statement that checks whether a number is positive:
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
In this example, the condition number > 0
evaluates to true
, so the message “The number is positive.” will be printed to the console.
If and else Statement
You can also use an else
statement to specify a block of code that should be executed if the condition in the if
statement is false
. Here is an example:
int number = -10;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is not positive.");
}
In this example, the condition number > 0
evaluates to false
, so the message “The number is not positive.” will be printed to the console.
You can also use an else if
clause to specify additional conditions. If the condition in the if
statement is false
, the else if
clause will be checked. Here is an example:
int number = 0;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
In this example, the condition number > 0
is false
, so the else if
clause is checked. Since the condition number < 0
is also false
, the code in the else
block is executed, and the message “The number is zero.” is printed to the console.