A conditional statement in Java evaluates a boolean expresion and executes corresponding code based on whether the condition is true or false.
Syntax of if Statement
The syntax for an if statement is as follows:
if (boolean_expression) {
// Code executed if boolean_expression evaluates to true
}
If the boolean expression evaluates to true, the block of code within the braces is executed. Otherwise, execution continues with the next statement after the if block.
Example
Below is the content of the file Test.java:
public class Test {
public static void main(String[] args) {
int number = 10;
if (number < 20) {
System.out.print("This is an if statement");
}
}
}
When copmiled and run, the output will be:
This is an if statement
if...else Statement
The if statement can be followed by a optional else block that runs when the condition is false.
Syntax
if (boolean_expression) {
// Executed if boolean_expression is true
} else {
// Executed if boolean_expression is false
}
Example
Here's the content of the file Test.java:
public class Test {
public static void main(String[] args) {
int number = 30;
if (number < 20) {
System.out.print("This is an if statement");
} else {
System.out.print("This is an else statement");
}
}
}
Output:
This is an else statement
if...else if...else Statement
Multiple conditions can be checked using a chain of if...else if...else statements.
Syntax
if (expression1) {
// Executed if expression1 is true
} else if (expression2) {
// Executed if expression2 is true
} else if (expression3) {
// Executed if expression3 is true
} else {
// Executed if all previous expressions are false
}
Example
Code in Test.java:
public class Test {
public static void main(String[] args) {
int value = 30;
if (value == 10) {
System.out.print("Value of X is 10");
} else if (value == 20) {
System.out.print("Value of X is 20");
} else if (value == 30) {
System.out.print("Value of X is 30");
} else {
System.out.print("This is an else statement");
}
}
}
Output:
Value of X is 30
Nested if...else Statements
Nested conditional blocks are allowed in Java, meaning an if or else if block can contain another if or else if statement.
Syntax
if (expression1) {
// Executed if expression1 is true
if (expression2) {
// Executed if expression2 is also true
}
}
You can nest else if...else just like regular if statements.
Example
Code in Test.java:
public class Test {
public static void main(String[] args) {
int x = 30;
int y = 10;
if (x == 30) {
if (y == 10) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
Output:
X = 30 and Y = 10