Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If-else and Switch!!

 
Brian Smith
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
thanks.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
switch can only be used with a short, byte, int or char so that may have some influence on your decision.
 
Erik Pragt
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html 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.
Erik
edit: I also found another link which might be useful: http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/2001/sept01.html#basics
[ June 17, 2003: Message edited by: Erik Pragt ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64844
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
bear
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic