Java if- else Statement
In Java, the if
statement is a control structure that allows you to execute a block of code conditionally, based on the value of a boolean expression. The if
statement has the following syntax:
if (boolean-expression) {
// code to be executed if boolean-expression is true
}
You can also use the else
clause to specify an alternative block of code to be executed if the boolean expression is false
. The else
clause has the following syntax:
if (boolean-expression) {
// code to be executed if boolean-expression is true
} else {
// code to be executed if boolean-expression is false
}
Here is an example of an if
statement in Java:
int x = 5;
if (x > 0) {
System.out.println("x is positive");
}
Output:
x is positive
In this example, the if
statement checks if the value of x
is greater than 0
. Since x
is indeed greater than 0
, the code inside the if
block is executed and the message "x is positive" is printed to the console.
You can also use the else
clause to specify an alternative block of code to be executed if the boolean expression is false
. For example:
int x = -5;
if (x > 0) {
System.out.println("x is positive");
} else {
System.out.println("x is not positive");
}
Output:
x is not positive
In this example, the value of x
is negative, so the code inside the else
block is executed and the message "x is not positive" is printed to the console.
The if
statement is a powerful control structure that allows you to write code that can adapt to different conditions and execute different blocks of code depending on the values of variables and other expressions.
Find out more about Java here: