You all have used both into c/c++.In simple words we can say that nested if is one type of if statement inside which there is another if statement.There may be else part at end of every if statement’s block of code.In if-else-if there are three control statements are used mainly.First is if,second is else-if and third one is if with else part.







Nested ifs :– 

There may be several possible output so for that we can use nested ifs.It uses if else statements inside if statements.

Syntax:

if(condition)
{
if(condition)
{
statements;
}
else
{
statement;
}
}

Example:

if(a>3)
{
if(a>5)
{
system.out.println(“a is big”);
}
else
{
System.out.println(“a is not big”);
}
}

The if-else-if ladder:-

It is the combination of three java control statement.


Syntax:-

if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;

Example:-


if(a==3)
System.out.println(“a is 3”);
else if(a==4)
System.out.println(“a is 4”);
else
System.out.println(“a is unknown”);

I think its easy to use.There may be no problem while using it.The syntax is easy to remember.



Lets execute one simple example which include both statement nested ifs and if-else-if ladder

Problem:-Find maximum number from three numbers given by user in java



Code–>>

import java.util.Scanner;
class nested{
public static void main(String args[]){
Scanner num=new Scanner(System.in);
int i,j,k;
i=num.nextInt();
j=num.nextInt();
k=num.nextInt();
if(i>j)
{
if(i>k)
{
System.out.println(i+” is maximum”);
}
else
{
System.out.println(k+” is maximum”);
}
}
else if(j>i)
{
if(j>k)
{
System.out.println(j+” is maximum”);
}
else
{
System.out.println(k+” is maximum”);
}
}
else
{
System.out.println(k+” is maximum”);
}
}
}

Output:-

output image



1
2
3
3 is maximum

Logic:-


First you have to understand the concept of scanner file.Here first we have included one java library file by writing “import java.util.Scanner”. When you want to add something via user then you must have to use this file.In c/c++ it is automatically added in standard file,but for java we have to add this file from java library.Now in main we have to create one variable or we can say one object of that file.So we have created one object of that file with using new operator.Now we have used three integer variable which will use Scanner file object with nextInt() command.If you want to add a line or Float number then you can use nextLine() or nextFloat() depending upon type.After initialising it we have used if else-if and else statements for finding out which is maximum.First it compares to variable and then depending upon the result it will compare it with another variable.Finally it will execute the given correct result.

  If you face any difficulty then contact us.Happy coding!

By jigar

Leave a Reply

Your email address will not be published. Required fields are marked *