If statement is used to execute a block of statements if the specified condition is true.
Syntax:
if(condition){ //Block of statements. }
Program to use if statement in Java.
public class IFExample { public static void main(String args[]){ int num1 = 10; int num2 = 20; if(num1 < num2){ //Print num1 if num1 < num2. System.out.println("Smaller number: " + num1); } } }
Output:
Smaller number: 10
If else
If else statement is used to execute either of two blocks of statements depending upon the condition. If the condition is true then if block will execute otherwise else block will execute.
Syntax:
if(condition){ //Block of statements1. }else{ //Block of statements2. }
Program to use if else statement in Java.
public class IFELSEExample { int num1 = 20; int num2 = 15; if(num1 < num2){ //Print num1 if num1 < num2. System.out.println("Smaller number: " + num1); }else { //Print num2 if num2 < num1. System.out.println("Smaller number: " + num2); } }
Output:
Smaller number: 15
If else if
If else statement is used to execute one block of statements from many depending upon the condition. If condition1 is true then a block of statements1 will be executed, else if condition2 is true block of statements2 is executed, and so on. If no condition is true, then else block of statements will be executed.
Syntax:
if(condition1){ //Block of statements1. }else if(condition2){ //Block of statements2. } . . . else if(conditionn){ //Block of statementsn. }else{ //Block of statements. }
Program to use if else if statement in Java.
public class IFELSEIFExample { public static void main(String args[]){ int num = 10; if(num == 10){ System.out.println("num is equal to 10."); }else if(num > 10){ System.out.println("num is greater than 10."); }else{ System.out.println("num is less then 10."); } } }
Output:
num is equal to 10.