Latest :

Java Switch Case Statement : Tutorial With Examples – Java Tutoring

Java Switch Case , generally used for one out of multiple options. Here we cover most of the information in a point of beginners perspective can easily understand. Java switch case with examples and sample Programs. Learn more about Java Tutorials and Java Beginners Programs.

If you need any more information about the java switch case statement do contact us or comment here at the end of the post our team will help you out.

NOTEThe following article post was published by Path Thomas , 25+ Years of experience in the field of Java programming , check out the table of contents.

1. Java Switch Case Statement Definition With Examples

  • Switch is a construction generally used to select one out of multiple options (an if-else ladder can also be used to select one out of multiple options). In that context, we can say switch is an alternative to if-else ladder. Switch is generally known as multi-way branch statement. Similar to if-else it is also a selection statement. Sample flow chart represented as : 
java-switch-statement

Source :stackoverflow.com

  • Switch Case is more suitable when a single expression is compared with multiple constants for equality. (if-else can be used for comparing variables, comparing ranges, etc; no limitations in if-else).

Generally Java switch case statement is felt as ‘easier to use’ compared with an equivalent if-else construction.

Below we share Syntax for java switch case with examples  :

[wp_ad_camp_3]

 

Switch Case Java Example Program – 1

Output:

Java switch case statement Example – 2

Output:

Another Example Program – 3

Output:

Java Switch case string example – 4

output:

 

Learn More

When control comes to a switch construction, it evaluates the expression in the header. Check out the following examples about the java switch case construction :

Examples :

[wp_ad_camp_3]

  • switch(2+3*4)     will be evaluated to switch(14)
  • switch(24/10)      will be evaluated to 2
  • switch(4)               will be evaluated to switch(4)
[wp_ad_camp_2]

The expression should result in an int or String type only. The system will accept byte, short, int and char types as int type. The long, float, double, and boolean are not accepted here. (if-else has no such limitation, it can work on any type of data). 

Check out the four examples that we are shared over here about switch case range :

  • switch(3.5)                          is not valid
  • switch(24/10.0)                 is not valid
  • switch(“smile”)                   is valid
  • switch((int)(3.5))                is valid

The evaluated result is compared with the available case labels for an equality match. When a match is found the statements corresponding to that case are executed. A break is used to come out of a switch construction.

For Example :  

 

  • In the above java switch case statement example, the switch case expression “himani” matches with the case “himani”, so the corresponding code will be executed and “laugh” will be printed as output. (the usage of String as case label is allowed from Java1.7 only. Older versions does not accept String here).

 

Another Java switch Case example as per above explanation : [ Example – 5 ]

Output:

Another Java switch char Program  with output : [ Example – 6 ]

Output:

Java Switch Case Int : [ Example – 7 ]

output:

  • If no case label is matched with the switch expression, then the default block is executed.

2. Example :  Important Points 

 

 

  • In the above example, the default part is executed and D is printed as 4 does not match with 1, 2 and 3..
  • The default part is optional. If we don’t want any action in case, no label is matched, then we can skip the default part. In case if none of the case label is matched and default part does not exist then no action will take place from the switch construction.
  • When break (or similar statement) is encountered then control comes out the switch construction. So generally a break statement is used at end of each case block.
  • If break is not placed, then system automatically enters into the next case block (even though the case label does not match with the switch expression) and executes statements there it self.

 

For Example :  

 

output:

 

  • In the above example, case 2 is matched. So, after printing “B”, it will automatically enters into case 3 and prints “C” as there is no break after case 2 block. But after printing “C”, control will come out because a break is found.

3. Invalid Ways Of Using Java Switch Case

 

Invalid Case – 1 :

  • We should not have two case labels with a same value. So the following are not valid.

Example :  1

 

Example : 2      

 

Example : 3  

 

Java Program Using Switch Case Statement [ Not Valid Examples ]

Invalid Case – 2 :

  • Not only the switch expression but also the case labels cannot have fraction part values. So the following code is also not valid.

 

Example :    

 

Invalid Case – 3

  • The switch expression can be a variable. But the case labels should always be constants only. Variables are not allowed to be case labels. Here is an example which results in error.

 

 

4. Default At Any Position

  • Generally the default part is placed at the end (after the last case block), but it can be placed anywhere. So the flowing code is fine.

Example :    

 

  • In the above example, if “exp” does not match with any case value, then the default part is executed. If we omit break at default part, then the control automatically executes statement C also (even though it is not matched). For example simple program here we shared :

Example Program :

Output:

Another Example Program – 2

Output:

5. Nested Switch Construction 
  • Similar to nesting of if-else, we can ” nest switch construction ” also. check out the syntax.

Syntax:

 

  • Generally, when we are writing an if-else construction, the curly braces are required to enclose the statements of an if/else block in case we have more than one statement.
  • But in switch construction, we can have any number of statements in a case block and they are not required to be enclosed within curly braces {}.

Example : 

 

6. Compatibility Of Switch Expression And Case Labels

Definition

  • Even though Java switch case can be applied on int types and String objects, when an int type is used as switch expression, its case labels should also be integers only. Similarly, when String is used as expression, labels should also be Strings only. A mismatch of this will raise a compilation error. The following code is invalid.

Example Program :

 

7. Same Code For Multiple Cases

  • Sometimes we need to execute a same code for different values. In that case we can write code as follows.

Example Valid Code :

 

Example Invalid Code* :

 

8. When To Use Switch Over If-Else

 

  • When we have more number of options then switch will be more efficient. We should not use just for 2 or 3 options (case labels) as the system needs some additional work inside to create a table for switch. Creating such a table for less number of elements is not efficient. But when we have more options switch case will be better than if-else.

Limitations of switch :

  • Not good for range comparisons.
  • Cannot work with all types of data.
  • Cannot work with variables as case labels.

 

Learn More

 

x

Check Also

Java If Else – Tutorial With Examples | Learn Java

If else Java – statement complete tutorial. Here we cover in-depth information with examples on ...