File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Cattle Drive and the fly likes Should I switch by ints or chars? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "Should I switch by ints or chars?" Watch "Should I switch by ints or chars?" New topic
Author

Should I switch by ints or chars?

Stuart Goss
Ranch Hand

Joined: Mar 21, 2001
Posts: 169
I was wondering, whether I should have my switch statement switch on a char or an int or even a short? Has anybody got an idea which one is best?
Stuart
Johannes de Jong
tumbleweed
Bartender

Joined: Jan 27, 2001
Posts: 5089
Stuart Switch requires that the value can be converted to int. Considering that char and short will need to be converted I assume that int will be best.
[This message has been edited by Johannes de Jong (edited July 23, 2001).]
Stuart Goss
Ranch Hand

Joined: Mar 21, 2001
Posts: 169
Are you sure that switch converts the expression? I looked in the java language specification... and I couldn't find anything.
The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.

But I suppose the expression is transformed into an integer in the byte code, or not?
I'm still not convinced, jdj
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
What are you gaining by using a short?


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1932
Switch takes anything that is int-compatible. Since the others can fit within an int, they work.
I agree with Marilyn, I've never used a short. The memory savings just aren't warranted to bother with the need for casting and such.
Jason
Stuart Goss
Ranch Hand

Joined: Mar 21, 2001
Posts: 169
So, unless I'm switching on chars like '+' or '-' there is no need to use char to switch on, I can just take an int. I'll do that next time, thanks a lot.
Stuart
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Should I switch by ints or chars?