Java supports the usual logical conditions from mathematics. You can use these conditions to perform different actions for different decisions. This is called conditional logic.
a < b (Less than)a <= b (Less than or equal to)a > b (Greater than)a >= b (Greater than or equal to)a == b (Equal to)a != b (Not equal to)Java has the following conditional statements:
if to specify a block of code to be executed, if a specified condition is true.else to specify a block of code to be executed, if the same condition is false.else if to specify a new condition to test, if the first condition is false.switch to specify many alternative blocks of code to be executed.if StatementUse the if statement to specify a block of Java code to be executed if a condition is true.
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
}
// Since the condition is false, nothing is printed.
}
}
else StatementUse the else statement to specify a block of code to be executed if the condition is false.
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
}
}
else if StatementUse the else if statement to specify a new condition if the first condition is false.
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
}
}
There is also a short-hand if-else, which is known as the ternary operator because it consists of three operands. It can be used to replace simple if-else blocks.
Syntax: variable = (condition) ? expressionTrue : expressionFalse;
int time = 20; String result = (time < 18) ? "Good day." : "Good evening."; System.out.println(result);