File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes switch statement 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "switch statement" Watch "switch statement" New topic

switch statement

Angela lewis
Ranch Hand

Joined: Mar 01, 2004
Posts: 100

Why does this code produce "default" and not 1 ?
Geoffrey Vlassaks

Joined: May 12, 2004
Posts: 24
That's because the unicode value of '1' will be taken to compare in the switch statement. This unicode value differs from 1, 2 and 3 so the default will be taken...

Wendal Park
Ranch Hand

Joined: Aug 28, 2001
Posts: 39
Geoffrey, I believe your explanation isn't quite correct.

The integer value of a char primitive is in fact the ASCII value of the character it represents. As it shows in the following code:

So even for char x = '1', the value x holds is the ASCII value of '1', which is 49.
[ May 25, 2004: Message edited by: Wendal Park ]

MSc, BSc, SCJP 1.4<br /> <img src="graemlins/banghead.gif" border="0" alt="[banghead]" /> SCBCD
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Wendal, the char does not have to be a ASCII character like 'a' or '1', it could be some value like \u0546 (whatever that is) which is way out of the ASCII range.

[ May 25, 2004: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Wendal Park
Ranch Hand

Joined: Aug 28, 2001
Posts: 39
Oh right, thanks for pointing out that.
I was just focusing on the single char (e.g. 'a') case which made me think of ASCII from the very beginning.
subject: switch statement
It's not a secret anymore!