File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference Between Switch and if else" Watch "Difference Between Switch and if else" New topic
Author

Difference Between Switch and if else

Ram Jeevi
Greenhorn

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: 14074
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference Between Switch and if else
 
Similar Threads
If-else and Switch!!
Puzzle anyone ???
What are the difference between Embeddable and One-to-one relationship.
Error in HTML escaping
Network question: switch and router