Home Java Java Switch Statement is now more Powerful | Java 18

Java Switch Statement is now more Powerful | Java 18

Published: Last Updated on 1 comment

Hey Tea Lovers! Today let me talk about the Plain Old Java Switch Expression, but with a twist. This twist or update has been added to the core library of Java since Java 13. And If you are using Java version 13 or after, you can surely convert that old switch with the new one.

I will talk about how it offers certain features in it without breaking existing changes. Of course, the other language users may comment “It was already there in our programming language years ago”. But let’s just smile, and continue coding in Java, shall we? One note, I will be using the “switch expression” and “switch statement” interchangeably in the post, so keep it in mind that I am trying to say the same thing.


I would be happy to connect with you guys on social media. It’s @coderstea on TwitterLinkedinFacebook, Instagram, and YouTube.

Please Subscribe to the newsletter to know about the latest posts from CodersTea.


Java Switch Latest Feature Requires

Before trying out this java switch feature, keep in mind it’s only available after Java 13. You can read more about How to install the latest Java on Install Latest or Any Java Version in 3 Simple Steps: Windows or How to Install Latest Java and Set JAVA_HOME on Ubuntu.

Also, look at the other latest features of Java on

Java 16 is Here! New Features of Java 16 Simplified

Java 17: These 5 New Features Make Java 17 Special

What’s new in Java 18? New Features of New Java 18

The Old Java Switch Statement

Ok guys, back to the basics. As you know the switch statement is to replace a if-else-if ladder for a single variable in a more readable and concise way (not every time). Yeah I know, this is not an exact definition, but I am not good at theory 😭. Please let me know in the comment the actual definition, I will surely update it here to save myself from more embarrassment.

Let’s see a practical example. Let’s say you pressed a button, and with that particular button code, you need to have some command associated with it. Now you can do if-else-if ladder shown in the first block, or convert it to the switch expression shown in the 2nd block.

If Else If ladder:

if(button == 1) {
    command = "on";
}
else if(button == 2){
    command = "off";
} 
else if(button == 3 || button == 4) {
    command = "ring";
}
else{
   throw new RuntimeException("Wrong Button Code"); 
}Code language: JavaScript (javascript)

Switch Expression:

switch(button){
    case 1:
        command = "On";
    break;
    case 2:
        command = "off";
    break;
    case 3:
    case 4:
        command = "ring";
    break;
    default:
        throw new RuntimeException("Wrong Button Code");
}Code language: JavaScript (javascript)

As you can see the switch is more readable and have less clutter. But even though we have reduced conditions check, we have to add a lot of extra code such as break statements. And this is where the new Java Switch statement or expression helps us. Well, more of an “updated switch expression” than a new one. But anyhow, let’s see them.

Java Switch Break, Please Take a Break

The first thing you will get to see in the new switch statement is that you don’t have to write the break statement at all. . To do that you have to use the arrow ->, the one we used in lambda, to tell the start of the case. As for the actual code block, you can either make it a one-liner expression or can have a curly bracket around the block.

Also, you don’t need to write case statements multiple times for the same evaluation of various cases, you can separate them with a comma (eg, cases 3 and 4 in the above example). Don’t believe me? See the code for yourself.

switch(button){
    case 1 ->  command = "on"; // on liner
    case 2 -> {
        // do something
        command = "off"; //  a block with curly brackets
    }
    case 3, 4 -> command = "ring"; //  case can be combined with a comma
    default -> throw new RuntimeException("Wrong Button Code");
}Code language: JavaScript (javascript)

See how concise the code has become. No extra break statement is needed. Also, cases can be combined without repeating the keyword. But wait, that’s not it. There is one more thing about this updated Java switch statement.

Yield from Java Switch Expression

Yes, you read it right. We can yield a result from a switch statement. Simply put, you can return something specifically from the switch block only. It uses Java 13’s newly added yield keyword for the switch statements. It is nothing but a return for the switch. You will better understand with an example.

Let’s say in the above examples, we were mutating the command variable for each case. Now instead of mutating the same variable, we can return the specific string from a certain case directly and assign it to command. And you can use both “colon case” and “arrow case” for it. Let’s see how.

Arrow case ->

String command = switch(button){
    case 1 -> {
        yield "on"; 
    } 
    case 2 -> {
       yield "off";
    }
    case 3,4 ->  {  // multiple case
        yield "ring";
    }
    
    default -> throw new RuntimeException("Wrong Button Code");
};Code language: JavaScript (javascript)

Colon Case :

String command = switch(button){
    case 1:
        yield "on";
        // no break should be used
    case 2:
        yield "off";
    case 3:
    case 4:
        yield "ring";
    default:
        throw new RuntimeException("Wrong Button Code");
};Code language: JavaScript (javascript)

Keep This in Mind While using Switch

How interesting it is isn’t it? But if you have noticed there are some conditions or ways you have to follow. Here they are.

  • You can’t interchangeably use colon and arrow cases in a single switch statement.
  • When yielding a result from an arrow case, you have to write it in curly brackets.
  • When yielding a result from a colon case, don’t use break keywords.
  • It is recommended to use an arrow case when using yield.
  • Follow CodersTea on Social Media and subscribe to our newsletter. 😜

Conclusion

That’s it for this post. I hope I was able to explain to you the new updates in switch statement or expression. It’s a minor but very helpful update. I know it’s not as powerful as Kotlin’s or Scala’s switch expression, but I think we can see it becoming more powerful in Java shortly. Till then let’s try using this thing in our code.

See you in the next post. HAKUNA MATATA!!!


I would be happy to connect with you guys on social media. It’s @coderstea on TwitterLinkedinFacebook, Instagram, and YouTube.

Please Subscribe to the newsletter to know about the latest posts from CodersTea.


Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ads
Ads
Ads

@2023 All Right Reserved. Designed and Developed by CodersTea

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More