Sunday, 22 January 2017

DECISION MAKING WITH IF...ELSE STATEMENT IN JAVA

The if...else statement is an extension of the simple if statement. The general form is
if(test expression)
true-block statement(s)
else
false-block statement(s)
If the expression is true, then the true block statement(s), immediately following the if statement are executed; otherwise the false-block statement(s) are executed. In either case, either true-block or the false-block will be executed, not both.

Example

import java.util.Scanner;
public class If2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a value");
int a = scan.nextInt();
System.out.println("Enter b value");
int b = scan.nextInt();
if(a>b)
{
System.out.println("a got a greater value");
}
else
{
System.out.println("b got a greater value");
}
}
}

Output -
Enter a value
10
Enter b value
5
a got a greater value


Nesting of if...else statement

When a series of decision is involved, we may have to use more than one if...else statement in nested form as follows :
if(test condition 1)
{
     if(test condition 2)
     {
          statement 1;
     }
     else
     {
          statement 2;
     }
}
else
{
statement 3;
}
statement-x;

If the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be executed; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x.

Example
import java.util.Scanner;
public class If3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter any number");
int num = scan.nextInt();
if(num>0)
{
if(num==0)
{
System.out.println("It is zero");
}
else
{
System.out.println("Number is greater than 0");
}
}
else
{
System.out.println("Number is less than 0");
}
System.out.println("Work completed");
}
}

Output -
Enter any number
5
Number is greater than 0
Work completed


The else if ladder

There is another way of putting if together when multipath decisions are involved. A multipath decision is a chain of 'if' in which the statement associated with each 'else' is an 'if'. It takes the following general form - 
if(condition 1)
     statement 1;
else if(condition 2)
     statement 2;
else if(condition 3)
     statement 3;
----------------------
----------------------
else if(condition n)
     statement n;
else
     default-statement;
statement-x;

Example -
public class If4 {
public static void main(String[] args) {
int num = -2;
if(num>0)
{
System.out.println("number is positive");
}
else if(num<0)
{
System.out.println("number is negative");
}
else
{
System.out.println("number is zero");
}
}
}

Output -
number is negative

No comments:

Post a Comment