The moose likes Beginning Java and the fly likes If-else and Switch!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "If-else and Switch!!" Watch "If-else and Switch!!" New topic

If-else and Switch!!

Brian Smith
Ranch Hand

Joined: Oct 26, 2002
Posts: 232
hi all;
what is the fundamental difference between if-else and switch? what is the specific situation that makes to choose one over the other?
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
switch can only be used with a short, byte, int or char so that may have some influence on your decision.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Erik Pragt
Ranch Hand

Joined: Sep 08, 2001
Posts: 125
Hello Namaste Sathi,
You can "Use the switch statement to conditionally perform statements based on an integer expression".
This means that you can have a short, byte, int or char as an input value, and execute a piece of code based on in input value using the 'case' statement. The advantage to using this over a if/else construct is that a switch statement usually looks better.
You can look at the first example at and magine how it would look if you would use an if else statement there.
I hope this made things a little clearer, if not, let me know.
edit: I also found another link which might be useful:
[ June 17, 2003: Message edited by: Erik Pragt ]
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
FYI: In the future, with Java 1.5, we'll be able to switch on an enum.
Mmmmm... enum... Don't they just sound nummy?

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
The old if-else-if-else is one situation that leaves me wishing Java was as good as COBOL(!) I loved the REXX "select" for years, but COBOL "evaluate" kicks *** for rich syntax. How could any modern language leave this stuff out?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63868

You never wrote in Bliss, did you?
Bliss (used extensively within DEC to write system software) had at least 6 variants of 'switch' that I can recall. Rich, but potentially confusing.

[Asking smart questions] [About Bear] [Books by Bear]
I agree. Here's the link:
subject: If-else and Switch!!
It's not a secret anymore!