Originally posted by Zac Roberts:
That's a great answer, thanks. Is it just me or are there some other situations where the compiler does check all of the cases, such is with a switch statement. I seem to remember that if you have a final variable that is declared but not initilized, you must initilize it in all cases for the code to compile correctly. Does anyone remember anything like this?
Hmmm...I'm not sure exactly what you mean, Zac. This is my best guess at what you're getting at:
In this case, the compiler has to look a little more closely at your code because a switch statement can be rather complex.
In this case, the final variable i is going to be used to initialize the variable k after the switch statement is complete. That switch statement is therefore responsible for initializing the final variable, i.
In order to be sure that i is initialized before it is used, every case in the switch statement must explicitly assign a veriable to i. (Or execution can "fall through" to a case which does.)
Try commenting out either line 1 or 2 or both.
You should see different results in each case. Commenting line 1 out will cause an error stating that the final variable i might not have been initialized before use. If you comment out line 2, you'll get an error because the final variable i might be assigned to twice, which is illegal. If you comment out both, it works fine - see if you can see why.
Also, you need to have a default case in order to ensure that i is set. I suppose, if you had a case for
every possible integer, you wouldn't have to but, if you try that, I'll see you next year when you're done typing.
I'm not sure if this is what you were talking about, but you can see that the compiler is forced to take some extra care when it comes to switch statements.
Corey