• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why use a switch statement over an if/else ladder? What is the benefit?

 
Greenhorn
Posts: 10
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi folks,

This is only my 3rd question on this forum, but you people are fantastic about answering quickly and with great clarity so thanks ahead of time!  My question is about when to use a "switch" statement over an "if else" ladder statement.  I think I have a fair grasp of how they work, but it seems to me that the switch statement saves no appreciable amount of coding over an if/else ladder, and the switch statement is limited to use with byte, short, int, String, char, and enum I think (I just remember those by thinking that you CANNOT use decimals, long, or boolean...all else is cool).  Also you can't use statements like  if(x > 4 && x < 9), which you CAN use in an if/else ladder.  

So....saves no real coding space, isn't simpler like a ternary statement is to an if/else statement, can't be used with as many variable types, and can't be used to make more complex decisions like if(x > 4 && x < 9).

Seems to me that the if/else ladder wins hands down.  What am I missing?  There must be some situation where it is of great advantage to use a switch statement or I'm guessing they wouldn't have invented it.

Thanks wise coding people!




 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Richard Attix wrote:I think I have a fair grasp of how they work, but it seems to me that the switch statement saves no appreciable amount of coding over an if/else ladder, and the switch statement is limited to use with byte, short, int, String, char, and enum I think (I just remember those by thinking that you CANNOT use decimals, long, or boolean...all else is cool).  Also you can't use statements like  if(x > 4 && x < 9), which you CAN use in an if/else ladder.  



In addition to the two restrictions you mentioned, the switch statement has one more. The targets, ie. the case statements, must also be compile time constants.

So, why would you choose a switch statement? Basically, a switch statement compiles to basically a jump table. This means, all of the case statements have the same latency. It is just as fast to get to the first case statement versus the last case statement.

This is not true for the if/then/else statements.The first conditional has much lower latency than the last conditional. The reason, of course, to get to the last else statement, it has to fail all of the many if/then/else statements prior to it.

Henry

 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Apart from the technical details that Henry pointed out, using if-else-if instead of switch-case in situations like this, where you have a list of values to check, is like using a pair of pliers instead of a specific-sized wrench to turn a bolt. The pliers may still work and, yes, it can be used in more applications than the fixed-sized wrench but the wrench really is the more appropriate tool.

For your example, however, a switch-case may not even be the most appropriate tool to use. I would argue that a map will allow you to write cleaner, less verbose code that has less duplication.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's what I mean about a map being more appropriate:

This code will behave exactly the same way as your previous examples, given valid values of day. The array of String is a poor man's map in this application: the array index is a fixed key. Using a real Map object would just move the verbosity in your examples from the lookup code to the setup code.
 
Marshal
Posts: 79177
377
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry for delay; I seem to have had a busy weekend.
The switch has the advantage which people have already mentioned of faster execution. An array and a Map both execute fast, but the array is easier to write. They also have the advantage that they permit their index/key be evaluated at runtime. The switch is specifically good for situations where the keys can be predicted in advance and specified at compile time. That is why, as Henry says, the cases must be compile‑time constants (officially called constant expressions).
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In case anybody wants more details, let's see what the JLS (=Java® Language Specification) has to say. All sorts of things, but not particularly helpful just at the moment. Maybe the JVM Specification will be more helpful. Well, it tells you the structure of the bytecode, so you can see how a switch is compiled into a lookup table.Note also how the fallthrough is compiled after cases 2 and 4. The goto 80 is missed out.
 
This will take every ounce of my mental strength! All for a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic