File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Difference Between Switch and if else Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference Between Switch and if else" Watch "Difference Between Switch and if else" New topic

Difference Between Switch and if else

Ram Jeevi

Joined: Nov 28, 2008
Posts: 7
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

Joined: Dec 17, 2003
Posts: 624

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

Joined: Aug 16, 2005
Posts: 15100

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 ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Difference Between Switch and if else
jQuery in Action, 3rd edition