Comparison operators are used with the conditional statement to evaluate a condition. Here are the comparison operators and their meaning:
==
!=
>
>=
<
<=
Equal to
Not equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java.
if statement
if-else statement
nested if statement
if-else-if ladder
In Java, an if statement is a conditional statement that runs a different set of statements depending on whether an expression is true or false.
Decision making is an important part of programming. It is used to specify the order in which statements are executed.
If else statements in Java is used to control the program flow based on some condition, it’s used to execute some statement code block if expression is evaluated to true, otherwise executes else statement code block.
The basic format of if else statement is:
Syntax:
if(test_expression) { //execute your code } else { //execute your code }
Java uses boolean variables to evaluate conditions. The boolean values true and false are returned when an expression is compared or evaluated.
A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
Syntax:
if( condition1 )
{
statement1; // BLOCK 1
}
else if( condition2 )
{
statement2; // BLOCK 2
}
else if( condition3 )
{
statement3; // BLOCK 3
}
else
{
statement4; // BLOCK 4
}
The above if conditions are executed top down. If the condition1 is true, only statement1 is executed, the other statements - statement2 and statement3 will not be executed.
If the condition1 is false and condition2 is true, then only statement2 is executed. If condition1, condition2 are false but condition3 is true, then only statement3 is executed. If all the conditions - condition1, condition2 and condition3 are false, then statement4 is executed.
Also note that when condition1 is true, irrespective of whether other conditions are true or false, only statement1 will be executed. statement2 and statement3 will not be executed.