Java Conditions and If Statements
Java supports the logical conditions from mathematics.
With the above logical conditions, we can perform different operations for different decisions.
Java has the following conditional statements:
The if statement
The if statement to specify a block of Java code to be executed if a condition is true.
Syntax
if (condition) { // block of code to be executed if the condition is true }
Example
if (10 > 5){ System.out.println("10 is greater than 5"); }
Output
10 is greater than 5
The else statement
The else statement to specify a block of Java code to be executed if the condition is false.
Syntax
if (condition) { // block of code to be executed if the condition is true } else { //block of code to be executed if the condition is false }
Example
if (10 < 5){ System.out.println("10 is less than 5"); } else { System.out.println("10 is greater than 5"); }
Output
10 is greater than 5
The else if statement
The else if statement to specify a new condition if the first condition is false.
Syntax
if (condition) { // block of code to be executed if the condition is true } else if { // block of code to be executed if the first condition is false } else { //block of code to be executed if the previous condition is false }
Example
if (time < 10){ System.out.println("Good morning"); } else if (time < 20) { System.out.println("Good day"); } else { System.out.println("Good evening"); }
Output
Good day
If there is only one statement to execute, one for if, and one for else, can be put together in a single line.
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Example
int time = 15; String result = (time < 18) ? "Good day" : "Good evening"; System.out.println(result);
Output
Good day