Explain switch statement in java language?
Switch statements are shorthands for a certain type of if
statement. It is not common to see a stack of if
statements all related to the similar quantity like this:
if (x == 0) doSomething0();
else if (x == 1) doSomething1();
else if (x == 2) doSomething2();
else if (x == 3) doSomething3();
else if (x == 4) doSomething4();
else doSomethingElse();
Java has a shorthand for these kinds of multiple if
statements, the switch-case
statement. Here's how you'd write the above using a switch-case
:
switch (x) {
case 0:
doSomething0();
break;
case 1:
doSomething1();
break;
case 2:
doSomething2();
break;
case 3:
doSomething3();
break;
case 4:
doSomething4();
break;
default:
doSomethingElse();
}
In this fragment x
must be a variable or expression in which can be cast to an int
without loss of precision. This means the variable must be or the expression must return an int
, byte
, short
or char
. x
is compared along with the value of each the case
statements in succession until one matches. This fragment compares x
to literals, other than these too could be variables or expressions as long as the variable or result of the expression is an byte
, int
, short
or char
. The default action is triggered if no cases are matched.
Once a match is found, all following statements are executed until the end of the switch
block is reached or you break out of the block. This could trigger decidedly unexpected behavior. Thus it is general to involve the break
statement at the end of each case block. It's excellent programming practice to put a break
after each one unless you explicitly want all following statements to be executed.
It's significant to remember that the switch
statement doesn't end while one case is matched and its action performs. A program then executes all statements in which follow in which switch
block until specifically told to break.