Introduction
Java executes all its programs in sequential order. Often, the flow of execution may depend on certain conditions that the programmer may want to impose. Decisional control statements require a condition to be fulfilled to execute the set of instructions that follow it. Relational and logical operators play an important role in setting such conditions. Relational operators are used to compare two operands and determine their relation.
Recommended Topic- Iteration Statements in Java, and Duck Number in Java.
The if statement
The if control statement allows the execution of a block of code only if it satisfies a given condition. If it does not fulfil the condition, the entire block is skipped. The use of if statement is the simplest way to modify the control flow of a program.
Syntax:
if(condition)
{
Statements of if block
}
Note: If there are no brackets to include the statements of the if block, only the first line after the if statement is executed as part of it.
Here is an example of the if statement in Java. Try it on online java compiler.
public class Main
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
{
int difference = 15-i;
System.out.println("The value is less than 15 by " + difference);
}
if (i == 15)
System.out.println("The value is = " + i);
System.out.println("End");
}
}
Output:
The value is less than 15 by 5
End
Also read - Jump statement in java
Nested if statements
They have an if statement inside another if statement. The inner block statements are executed only if both condition1 and condition2 are satisfied.
Syntax:
if(condition1)
{
Outer block Statements
if (condition2)
{
Inner block Statements
}
}
An example of nested if statements.
public class Main
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
{
if (i%2 == 0)
System.out.println("The value is an even number less than 15" +);
}
System.out.println("End");
}
}
Output:
The value is an even number less than 15
End
You can also read about Java Destructor and Hashcode Method in Java.