A Funny Java Flavoured Look at the World

Sunday, August 06, 2006

SCJP 5 - Switch Statements

I was curious about the effect of autoboxing on the switch statements and it has provided a potential exam gotcha. I was reading my SJCP book about control flow, if statements, switch statements and I was thinking to myself do I really need to read this stuff, I know it.

But there are a few cheeky things in there. Like you are now allowed to use Enums as well as anything Int and below.

Also if you use a byte you can’t use a value higher than 127 otherwise it throws an error.

I am a bit confused about the fact you need a constant. Initially I thought this meant the value you were testing in the select had to be a constant but now after a bit of investigation I understand (what a fool I have been) that the it'’s the case statements that need the constants.

I have also found that if you are testing a btye value in the select then you have to have byte constants in the case. Usually you don'’t notice because you use ints.

My investigation into the realms of the Wrapper classes and shown me that you can indeed use a wrapper class value in the select statement. Autoboxing unboxes the value and changes it to the primative.

Finally a few Switch statement gotcha's

1. You can't have to case constants with the same value, it will throw a compiler error
2. Case Constants are evaluated from the top to the bottom.
3. The default constant can go anywhere and remember it is an entry into the code, so without any break statements it will run all the code below in the other case statements.

1 Comments:

  • Please check for typos, gramatical mistakes before publishing it. Its really difficult to read (or, understand) when one misses a word from a sentence. It really consumes useless time in re-phrasing a sentence.

    By Anonymous Anonymous, at Wed Aug 16, 06:58:00 am 2006  

Post a Comment

<< Home