Switch case in java

Previous
Next

Switch case in java is alternative to if else if ladder. It is used to execute statements based on some conditions.

Syntax of Switch case in java:

Let’s understand it with the help of simple example.
We are going to print weekday based on integer. 0 represents Sunday, 1 represents Monday and so on..

Output:

Friday

As we have highlighted in syntax, break keyword is optional.
Let’s see what happens if we do not use break statement.

Output:

Friday
Saturday
Invalid day of week

As you can see here, if you do not use break statement, it will execute all the statements once condition is met.

Switch case String example:

You can use String also in expression from Java 7 onwards.
Let’s understand with help of simple example:

Output:

Friday

Switch case uses equals method comparison internally, so case statement is case sensitive here.

Choosing between Switch case and if else if depend on readability and various factors. You can choose as per your need.

that’s all about switch case in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog