• 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

The switch statement

 
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1) Why does it accept ONLY compile time constants ?
2) Is it EXACTLY like multiple if-else checks ?
Consider an eg. switch gets int 9. cases are 3 to 15. Does the switch compare 7 with each int from 3 to 9 ? Or does it do something else ?
3) Which is faster : many if-else or switch ? How to measure that speed ? Is that measurement of any practical value ?

< I have strong doubts if we can measure it correctly, because the processor has so many things to do besides the if-else/switch. All the time for those activities might affect our values.
Can we tell the processor - NOW, GO ONLY THROUGH THE IF-ELSE TILL ITS END (WHILE A STOPWATCH MEASURES THE TIME). Any thoughts on this ? >
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The reason why it accepts only compile-time constants has to do with how the switch statement works under the covers. It enables the Java compiler and JIT to implement the switch via a branch table. The constants must be known at compile time for the compiler to be able to set up the branch table.

Logically, it does the same as multiple if ... else if ... statements. Under the covers, it doesn't work in the same way. A switch statement is probably more efficient than a chain of if ... else if ... statements.

I wouldn't try to force my code into a switch statement just because I suspect that it is faster - that's premature optimization.
 
If you want to look young and thin, hang around old, fat people. Or this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic