else if Statement in Java

We can qualify the else clause in the previous section by adding a further condition to be satisfied for the subsequent statements to be executed. This is done by using an else if clause in place of the else clause. This has the following construct:

if (condition1)
{
one or more statements to be executed if condition1 is true;
}
else if (condition2)
{
one or more statements to be executed
if condition1 is false and condition2 is true;
}


Any number of else if clauses can be associated with the first if clause, and these may be optionally followed by an else clause. For example, we can modify Calculate Product to handle three conditions: one argument supplied, two arguments supplied and zero, three or more arguments supplied. For Example;

CalculateProduct

public class CalculateProduct
{

public static void main(String[] args)
{
int arg1;
int arg2;
int result;
if (args.length == 1)
{
arg1 = Integer.parseInt(args[0]);
result = arg1 * arg1;
System.out.println("Square of " + args[0] + " is"+ result);
}
else if (args.length == 2)
{
arg1 = Integer.parseInt(args[0]);

arg2 = Integer.parseInt(args[1]);
result = arg1 * arg2;
System.out.println(''Product of " + args[0]
+ " and " + args[1] + " = " + result);
}
else
{
System.out.println(
"Please supply one or two arguments");
}
System.out.println("no of args = " + args.length);
}
}

No comments:

Post a Comment