Java
supports the usual logical conditions from mathematics:
- 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: a != b
In
programming, it's often desirable to execute a certain section of code based
upon whether the specified condition is true or false during the run time. For
such cases, control flow statements are used. There are various types of if
statement in java.
- if statement
- if-else statement
- if-else-if ladder
- nested if statement
if
statement
The
Java if statement tests the condition. It executes the if block if condition is
true.
Syntax
if (condition)
{
// code to be executed
}
Example
public class Test {
public static void
main(String[] args) {
int a = 30;
int b = 20;
if (a > b) {
System.out.println("a is greater than b");
}
}
}
Output: a is greater b
if-else
statement
The
if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax
if (condition)
{
// code if condition is true
} else {
// code if condition is false
}
Example
public class Test {
public static void main(String[] args) {
int a = 30;
int b = 20;
if (a > b) {
System.out.println("a is greater than b");
}
else {
System.out.println("b is greater than a");
}
}
}
Output: b is greater than a
Using
Ternary Operator
We
can also use the ternary operator (? :) to perform the task of if...else statement.
It is a shorthand way to check the condition. If the condition is true, the
result of ? is returned. But, if the condition is false, the result of : is
returned.
public class Test {
public static void
main(String[] args) {
int a = 30;
int b = 20;
String
str = a > b ? "a is greater than b" : "b is greater than a";
System.out.println(str);
}
}
if-else-if
ladder Statement
The
if-else-if ladder statement executes one condition from multiple statements.
Syntax
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if all the conditions are false
}
Nested
if statement
The
nested if statement represents the if block within another if block. Here, the
inner if block condition executes only when outer if block condition is true.
if (condition1) {
// code to be executed
if (condition2) {
// code to be executed
}
}