Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
The else if condition is checked only if all the conditions before it (in previous else if constructs, and the parent if constructs) have been tested to false.
Example: The else if condition will only be checked if i is greater than or equal to 2.
Syntax :
if ( condition 1 )
{
// block of statement to be executed if condition is true ;
}
else if ( condition 2 )
{
// block of statement to be executed if the condition1 is false condition2 is true ;
}
else
{
block of statement to be executed if the condition1 is false condition2 is False ;
}
The program begins by declaring a variable avg to store the user input for average marks. It then prompts the user to enter the average mark using the System.out.println() statement.
The program then creates a Scanner object called in to read the user input from the console. The in.nextFloat() method reads the input as a floating-point number and stores it in the avg variable.
Next, the program uses a series of if-else statements to check the value of avg and print the corresponding grade. The first if statement checks if the average is between 90 and 100 (inclusive) and prints "Grade A" if true. The subsequent else if statements check if the average is within the ranges for grades B and C and print the corresponding grades if true. Finally, if none of the conditions are true, the program prints "Grade D".
Overall, this program provides a simple example of using if-else statements to perform conditional operations in Java.
import java.util.Scanner; /* Else If Ladder 90-100 Grade-A 80-89 Grade-B 70-79 Grade-C <70 Grade-D */ public class else_if { public static void main(String args[]) { float avg; System.out.println("Enter The Average Mark : "); Scanner in = new Scanner(System.in); avg = in.nextFloat(); if (avg >= 90 && avg <= 100) { System.out.println("Grade A"); } else if (avg >= 80 && avg <= 89) { System.out.println("Grade B"); } else if (avg >= 70 && avg <= 79) { System.out.println("Grade C"); } else { System.out.println("Grade D"); } } }
Enter The Average Mark : 84 Grade BTo download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions