Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference Between Switch and if else

 
Ram Jeevi
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi team
Can some one say me the main difference between Switch case and if else statement. Which one is more efficient and why?

Thanks in advance
Ram Jeevi
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the main differences is that a switch allows for cumulative actions via fall through.

Also switches only work for tests on byte, short, char, and int primitive data types, as well as enumerated types (i.e. Enums). (Although there was a proposal for a new feature in Java 7 to allow the use of Strings in Switches. We'll have to see if that actually happens.)

I do not believe one is any more efficient than the other. The choice of using a switch statement of a if/if-else/.../if-else/else block is one of which is easier to read and understand. In some cases a Switch statement allows for cleaner code that is more readily apparent as to what is being done. But to be honest, switch statements are not used a whole lot. Many developers even forget they exist
[ December 11, 2008: Message edited by: Mark Vedder ]
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15437
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do the same kind of things with a switch statement and a set of if / else if statements.

Don't choose one over the other because you think one is more efficient than the other. Such micro-optimizations almost never make sense. I agree with Mark that you should choose whatever makes your code easier to read and understand.
[ December 12, 2008: Message edited by: Jesper Young ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic