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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…