The if-else-if ladder statement is used to test multiple conditions in Java. It’s used to test a single condition from a set of statements.
When there are multiple conditions to execute, the if-else-if ladder makes the code easy to understand and work with.
Syntax:
if(condition1)
{
//code for if condition1 is true
}
else if(condition2)
{
//code for if condition2 is true
}
else if(condition3)
{
//code for if condition3 is true
}
...
else
{
//code for all the false conditions
}
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
float percent;
System.out.println("Enter number:");
percent =sc.nextFloat();
if(percent >95 )
{
System.out.print(" PASS - A+");
}
else if(percent<=85 && percent >75){
System.out.print(" PASS - A");
}
else if(percent<=75 && percent >65){
System.out.print(" PASS - B");
}
else if(percent<=65 && percent >55){
System.out.print(" PASS - C");
}
else if(percent<=45 && percent >35){
System.out.print(" PASS - D");
}
else if( percent <35){
System.out.print(" FAIL - F");
}
}
}
Various inputs:
Enter number:78
PASS - A
Enter number:97
PASS - A+
Enter number:
31
FAIL - F
A nested if statement is an if inside another if statement. In this case, one if block is placed inside another if block, and only the inner block is executed if the outer block is true.
Syntax:
if(condition)
{
//statement
if(condition)
{
//statement
}
}
import java.util.Scanner;
public class IfDemo1 {
public static void main(String[] args)
{ Scanner sc=new Scanner(System.in);
char gender;
float age;
System.out.println("enter gender and age: ");
gender=sc.next().charAt(0);
age=sc.nextFloat();
if(gender == 'M')
{
if(age>=20)
System.out.print("Can be married legally");
else
System.out.print("Cannot be married ");
}
else if(gender=='F'){
if(age>=20)
System.out.print("Can be married legally");
else
System.out.print("Cannot be married ");
}
else{
System.out.print("Invalid ");
}
}
}
enter gender and age:
F 32
Can be married legally
Note: also read about the Selection Statement
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given two singly linked lists that intersect at some node. Your task is…
A builder plans to construct N houses in a row, where each house can be…
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…