The if else construct is used if we wish to execute one set of statements if a condition is true, and a second set of statements if the condition is false. The basic format of the if else construct is as follows:
if (condition)
{
one or more statements to be executed if condition is true;
}
Else
{
one or more statements to be executed if condition is false;
}
To illustrate this, the CalculateProduct example calculates the square of an input argument if just one argument is supplied to the program; otherwise, it calculates the product of the first and second arguments.
Calculate Product
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
{
arg1 = Integer.parseInt(args[0]);
arg2 = Integer.parseInt(args[1]);
result = arg1 * arg2;
System.out.println(''Product of " + args[0] +" and " + args[1] + " = " + result);
}
System.out.println("no of args = " + args.length);
}
}
if (condition)
{
one or more statements to be executed if condition is true;
}
Else
{
one or more statements to be executed if condition is false;
}
To illustrate this, the CalculateProduct example calculates the square of an input argument if just one argument is supplied to the program; otherwise, it calculates the product of the first and second arguments.
Calculate Product
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
{
arg1 = Integer.parseInt(args[0]);
arg2 = Integer.parseInt(args[1]);
result = arg1 * arg2;
System.out.println(''Product of " + args[0] +" and " + args[1] + " = " + result);
}
System.out.println("no of args = " + args.length);
}
}
No comments:
Post a Comment