Switch Case

  • Eclipse: Oxygen
  • Java: 1.8

Switch case statement in java is the conditional statement which executes one statement out of many statements when the condition is matched. Default statement is executed when none of the condition is matched.

Syntax

Example

Switch case always works on condition, here condition is int x = 3. When we execute the program, condition matches with case 3, so the output is

Output

The value of x is 3

The value of x is other than 1,2,3

Surprised with the output.  So here is a catch that statement after the matched condition will also execute. To get rid of this condition switch case is always used with a break statement.

Break statement

The break statement is used to come out of the program flow. The line at which program finds the break statement, it comes out of the execution flow and ignores the rest cases. It is optional to use a break statement after the default statement but it is recommended.

Example

With the use of the break statement, the program will come out of flow after the matched case is executed.

Output

The value of x is 3

Do you Know?

 It is not necessary to write case statements in sequence.

Only int, char, String, and Enum are allowed as switch expression.

 

In the following example, we will see the use of characters in the switch case. We write ‘a’ (lower case) as a condition for switch case.

Output: The value of x is a.

If you write a condition like char x = ‘A’ (upper case).

Output

The value of x is other than a, b, c.

In programming, lower case and upper case character are evaluated differently. In below example, we will see how to condition to get rid of such situation.

Output

The value of x is a.

String as an expression

A String can be used as an expression in a switch statement.  This switch statement expression is compared with the expression of each case.  This comparison is case sensitive, so we convert all expressions into lower case.

Contributed by: Poonam Tomar


VIEW COURSES

Buy me a coffee!

 

PayTM QR (INDIA)

  • Get video tutorials
  • Project files set
  • Get Certified

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu