if-else-if ladder:
- Used to defined multiple if blocks.
- One if block execution depend to another if block.
- All the conditions execute sequentially from top to bottom.
- A specific block execute only if the corresponding condition is valid.
Syntax:
if (condition){
Logic….
}
else if (condition){
Logic….
}
else if (condition){
Logic….
}
else{
Logic…
}
Flow Chart:
Code program:
class Conditional
{
public static void main(String[] args)
{
if (false)
System.out.println("if-block");
else if (true)
System.out.println("else-if block");
else
System.out.println("else block");
}
}
Check the input number is positive or negative:
class Test
{
public static void main(String[] args)
{
int num=-13;
if(num>0)
System.out.println("Positive number");
else if(num<0)
System.out.println("Negative number");
else
System.out.println("Zero");
}
}
Biggest of 3 numbers:
class Conditional
{
public static void main(String[] args)
{
int a=10, b=30, c=20 ;
if (a>b && a>c)
System.out.println("a is big");
else if (b>c)
System.out.println("b is big");
else
System.out.println("c is big");
}
}
Leap Year:
- 400 multiples are leap years
- 4 multiples are leap years
- 100 multiples are not leap years (100,200,300,500,600,700,900..)
class Test
{
public static void main(String[] args)
{
int yr = 100;
if(yr%400 == 0)
System.out.println("Leap year");
else if(yr%4==0 && yr%100 != 0)
System.out.println("leap year");
else
System.out.println("not leap year");
}
}