This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The switch build the "if" cases structure based on compilation time (for example you cannot change a or b on runtime). In your second code you have a compilation error because the b variable is not initialized at the compilation time. The compiler cannot know that you will initialize it later.
Joined: Apr 09, 2006
Before using the constant it has assigned with the value 2.
Joined: Feb 28, 2007
The case constant must be compile time constant, because the case argument has to be resolved at compile time. The variable that has to be used in the case must be assigned a literal at the time it is declared.
final int b; a=10; //b is not compile time constant because it is assigned the value at run time.