Java switch case

In day to day life , sometimes our action depends on some condition being met. Example: If he has holiday, we will go for movie OR If it is raining , I will open the umbrella OR If I get job, I will give you party etc.

In java there are conditional statements which helps to perform action on some condition being met and those are listed below.

  1. if
  2. if else
  3. switch

The control statement that allows us to make a decision from the number of choices is called a switch or switch case. switch is Implemented using keywords switch, case and default. switch expression can be integer or float or char or string and value of case must be compatible with switch expression. Each value of case must be unique means duplicate values are not allowed .General form of switch is given below:

The value of the expression is compared with each of the values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the value in case matches the value of the expression, then the default statement is executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken.The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement.

In switch duplicate values of case are not allowed, which is shown in below example.

When expression value is not match with none of the value of case than default block gets executed which is shown in below example.

You may also like...

Leave a Reply