If Else in Java Tutorial
Java has the following conditional statements of If else in java
-
if is used to specify a block of code if the condition is true
-
else if is used to specify a block of code if the first condition is false
-
else is used to specify a block of code if the conditions from if and else if are false
The if statement
How is the if else in Java works? if is used to execute a block of code if the condition is true. See this example code below.
Example code
package ifelse; import java.util.Scanner; /** * * @author KENSOFT */ public class IfElse { public static void main(String[] args) { System.out.print("Rate from 1 - 10: "); Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if(n >= 8 && n <= 10){ System.out.println("Excellent"); } } }
That is an example of executing an if statement in Java
Output
Rate from 1 - 10: 10 Excellent
The else if statement
How the else if statement works? else if is used to execute a block of code if the first condition is false. See this example code below.
Example code
package ifelse; import java.util.Scanner; /** * * @author KENSOFT */ public class IfElse { public static void main(String[] args) { System.out.print("Rate from 1 - 10: "); Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if(n >= 8 && n <= 10){ System.out.println("Excellent"); }else if(n >= 5 && n <= 7){ System.out.println("Very Good"); } } }
That is an example of executing an if statement with else if statement in Java
Output
Rate from 1 - 10: 7 Very Good
The else statement
How does the else statement work? else is used to execute a block of code if the condition of if and else if are false. See this example code below.
Example code
package ifelse; import java.util.Scanner; /** * * @author KENSOFT */ public class IfElse { public static void main(String[] args) { System.out.print("Rate from 1 - 10: "); Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if(n >= 8 && n <= 10){ System.out.println("Excellent"); }else if(n >= 5 && n <= 7){ System.out.println("Very Good"); }else if(n >= 3 && n <= 4){ System.out.println("Good"); }else if(n >= 1 && n <= 2){ System.out.println("Bad"); }else{ System.out.println("Rating is out of scope"); } } }
Output
Rate from 1 - 10: 11 Rating is out of scope
That’s how you do If else in Java.