‘if, if…else, if…else…if‘ statements is used to control the flow of a program. This is used to execute a particular block of code in the program if certain condition is fulfilled. ‘if‘ statement executes a particular block of code if the condition in the if statement is true. When condition is false the code for the if statement does not get executed. The following program shows the use of if statement.
package com.company;
public class IfElseStatement {
public static void main(String[] args) {
int i = 4;
if (i > 2) {
System.out.println("The number is greater than 2 ");
}
}
}
Output:
The number is greater than 2
If the condition in the if statement is not satisfied an else statement can be used to execute a block of code. The following program shows the use of ‘if…else‘ statement.
package com.company;
public class IfElseStatement {
public static void main(String[] args) {
int i = -2;
if (i > 0) {
System.out.println("The number is a positive integer");
} else {
System.out.println("The number is a negative integer");
}
}
}
Output:
The number is a negative integer
The ‘if…else…if‘ statement is used to execute a particular block of code on certain conditions. ‘if‘ statement is executed first and when the condition is false it moves to the else if statement. If none of the ‘else if‘ statement satisfies the condition then statement in the else is executed. The following program shows the use of ‘if…else…if‘ statement.
package com.company;
public class IfElseStatement {
public static void main(String[] args) {
int i = 2;
if (i > 0) {
System.out.println("The number is a positive integer");
} else if (i < 0) {
System.out.println("The number is a negative integer");
} else {
System.out.println("The number is 0");
}
}
}