Decision Statement or selection statement allow you to take a decision as which statement will to be executed next. It select one block of statements out of many blocks. Decision statement includes: if, if-else, nested-if, and switch statement.
If statement - Specifies the condition and execute the statements only if the condition is true, and if the condition is false, statements will not be executed.
if (condition) { statement 1; statement 2; . . statement n; }
Example 1: Program to check the user is eligible for vote or not.
package ifstatement; public class Ifstatement { public static void main(String[] args) { int n=20; if(n>=18) System.out.println("User is eligible for vote"); } }
Java if-else condition: it is divided into 2 parts: true and false. If the condition is true first block of code will executed and if the condition is false then second part of block will be executed. Both parts of statements will not be executed in either condition. Syntax:
if (condition) { statement 1; statement 2; . . statement n; } else { statement 1; statement 2; . . statement n; }
Example 2: Re-write the above Example 1 using if-else condition.
package ifstatement; public class Ifstatement { public static void main(String[] args) { int n=15; if(n>=18) System.out.println("User is eligible for vote"); else System.out.println("User is not eligible for vote"); } }
Java Nested if - It is useful when multiple conditions are to be applied.
if (condition 1) { statement 1; } else if (condition 2) { statement 2; } else { statement 3; }
In the above example, if condition 1 is true first block of statements will be executed, rest of the condition will not executed nor checked. If condition 1 is false and condition 2 is true, than 2nd block of Statements will be executed. If the condition 1 and condition 2 is false than 3rd block of statements will execute.
Example 3: Find greater number from 3 numbers.
package ifstatement; public class Ifstatement { public static void main(String[] args) { int a=10, b=25, c=20; if(a>b && a>c) System.out.println("A is greater"); else if(b>a && b>c) System.out.println("B is greater"); else System.out.println("C is greater"); } }
Example 4: Input 3 numbers and find greater number.
package ifstatement; import java.util.Scanner; public class Ifstatement { public static void main(String[] args) { int a, b, c; Scanner scan = new Scanner(System.in); System.out.println("Enter 3 numbers: "); a = scan.nextInt(); b = scan.nextInt(); c = scan.nextInt(); if(a>b && a>c) System.out.println("A is greater"); else if(b>a && b>c) System.out.println("B is greater"); else System.out.println("C is greater"); } }