If - else statement (Part 2)
Java if-else Statement
The Java if-else statement tests the condition , it executes the if block if condition is true otherwise else block is executed.
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
}
Flowchart:-
public class MyClass {
public static void main(String args[]) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
}
else {
System.out.println("Good evening.");
}
}
}
Output:-
Good day.
Ternary Operator
In place of if-else sometimes ternary operator is used as it replaces multiple lines of code into a single line
Syntax:-
variable = (condition) ? expressionForTrue : expressionForFalse;
Eg:-
Above block of code by replacing if-else with ternary operator can be written as:
int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
It will generate the same output.