Switch Statement in Java

Another type of branching construct is the switch statement. This takes the form

switch (expression1)
{
case value1:
one or more statements to be executed;
break;
case value2:
one or more statements to be executed;
break;
default:
one or more statements to be executed;
break;
}


expression1 is a char, byte, short, or int expression evaluated by the switch statement. If this is equal to value1, the statements following the case value1: clause are executed. If expression1 evaluates to value2, the statements following case value2: are executed. Of course, there can be any number of case statements. If the value of expression1 is not included in any of the case statements, then the statements following default: are executed

The break statement ensures that program execution continues with the statement following the entire switch block.without a break statement after executing the corresponding case statement, control would pass to subsequent case statements. As an example, the second version of CalculateProduct has been rewritten using the switch statement: the result is shown by using the CalculateProduct example.

CalculateProduct


public class CalculateProduct
{

public static void main(String[] args)
{

int arg1;
int arg2;
int result;

switch (args.length)
{
case 1:
arg1 = Integer.parseInt(args[0]);
result = arg1 * arg1;
System.out.println(''Square of " + args[0] + " is"+ result);
break;
case 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);
break;
default:
System.out.println( "Please supply one or two arguments");
break;
}

System.out.println(''no of args = " + args.length);
}
}

No comments:

Post a Comment