Switch case in java

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 it depends on readability and various factors. You can choose as per your needs.

that’s all about switch case in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *