- by Rutu Shah
In java programming, with if statement only the block of the statement which is true will be executed, however false block of code is not execute, therefore to overcome this we use if-else statement. If the specified condition is true then if block will be executed, and if specified condition is false, than else block of code will be executed.
Syntax
if (condition)
{
// execute if block of code if condition is true.
}else {
// execute else block of code if condition is false.
}
Example
You can find the code here
package com.qacaffe.examples.ControlStatements;
import java.util.Scanner;
public class IfElse {
public static void main(String[] args) {
//Input
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number to test whether the given number is bigger than 20.");
int number = scanner.nextInt();
if (number > 20) {
System.out.println("Congratulations !!! Number is bigger than 20.");
} else {
System.out.println("Sorry !!! The number which you entered is not bigger than 20, Please try again.");
}
System.out.println("Outside if - else block.");
}
}
/*
Output
(when entered number is less than 20)
Please enter a number to test whether the given number is bigger than 20.
18
Sorry !!! The number which you entered is not bigger than 20, Please try again.
Outside if - else block.
(when entered number is greater than 20)
Please enter a number to test whether the given number is bigger than 20.
33
Congratulations !!! Number is bigger than 20.
Outside if - else block.
*/
Explanation of code.
In the above program, firstly I am taking input from the user and then verifying whether the given number is greater than 20 or not. In the first output, I have entered number 12 so it is going to else part and the printing number is not bigger than 20, while In the second output, I have entered number 34 so is printing number is bigger than 20.