Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Nested IF and IF-ELSE-IF Ladder

Posted By: Jadwa Mansour     Category: Java     Views: 12727

This article explains about Nested If and If-Else-If Ladder in java with examples.

When an if statement is the target of another if or an else, it is said to be nested within the outer if.

Syntax of Nested IF

Form1 :
if(expression) statement;
  if(expression) statement;
    |
    |
    |
     if(expression) statement;

Form2 :
if(expression) statement;
else
    if(expression) statement;
    else
        if(expression)
|
|
|
else statement;


Examples of Nested IF statement , If-Else-If Ladder and IF-Else if ladder

Example 1 : Program that checks number is zero, positive or negative using nested if statement


class CheckSignNumberDemo 
{
   public static void main(String args[]) 
   {

int x = 10;

if(x > -1)
 if(x != 0)
   if(x > 0)
System.out.println("x is a positive number having value " + x);

   }


Output
x is a positive number having value 10

Example 2 : Program that checks number is zero, positive or negative using if-else-if ladder

class CheckSignNumberDemo 
{
   public static void main(String args[]) 
   {
int x = 10;

if(x <= -1)
System.out.println("x is a negative number having value " + x);
else 
if(x == 0)
System.out.println("x is a zero number having value " + x);
else
if(x > 0)
System.out.println("x is a positive number having value " + x);
   }


Output
x is a positive number having value 10

Example 3 : Program that prints number in word using if-else if ladder

class NumberInWordDemo 
{
   public static void main(String args[]) 
   {
int x = 3;

if(x < 0)
System.out.println("x is a negative number having value " + x);
else if(x == 0)
System.out.println("x is a zero number having value " + x);
else if(x == 1)
System.out.println("x is a positive number having value One");
else if(x == 2)
System.out.println("x is a positive number having value Two");
else if(x == 3)
System.out.println("x is a positive number having value Three");
   }


Output
x is a positive number having value Three


  
Share: 


Didn't find what you were looking for? Find more on Nested IF and IF-ELSE-IF Ladder Or get search suggestion and latest updates.

Jadwa Mansour
Jadwa Mansour author of Nested IF and IF-ELSE-IF Ladder is from Karachi, Pakistan.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!