Possible Duplicate:Should I use switch statements or long if…else chains? I'm working on a small program that will conduct an Insertion Sort. A number will be inputted through the keyboard and stored in a variable I called num. I've decided to use a switch statement in order to obtain the number inputted.switch( e.getKeyCode() ) {    case KeyEvent.VK_0: num = 0; break;    case KeyEvent.VK_1: num = 1; break;    case KeyEvent.VK_2: num = 2; break;    case KeyEvent.VK_3: num = 3; break;    case KeyEvent.VK_4: num = 4; break;    case KeyEvent.VK_5: num = 5; break;    case KeyEvent.VK_6: num = 6; break;    case KeyEvent.VK_7: num = 7; break;    case KeyEvent.VK_8: num = 8; break;    case KeyEvent.VK_9: num = 9; break;}I realized one other course of action could have been to use a set of if statements.if( e.getKeyCode() == KeyEvent.VK_0 )    num = 0;else if( e.getKeyCode() == KeyEvent.VK_1 )    num = 1;etc. for every number up until 9.I then wondered what the essential difference is between a switch statement and a series of if statements. I know it saves space and time to write, but it's not that much. So, my question is, aside from the space, does a switch statement differ from a series of if statments in any way? Is it faster, less error-prone, etc.?This question really doesn't affect my code that much. I was just wondering.Also, this question pertains to the JAVA language, not any other programming language. 
How is a switch statement better than a series of if statements?
java;switch statement
You are correct that functionally they are identical. Practically speaking though, why would you type (or cut and paste) all that when a switch statement is so much more concise?The difference is not one of functionality, but of intent. When you write a switch statement, you are in effect telling the reader that this section of code could branch multiple ways based on the state of one single variable. This statement is enforced by the compiler.When you write an if block, however, you are not deliberately stating that only one variable is involved. When you write a series of ifs, as you suggest, it is much harder to see that the branching is only based on a single variable. This is a maintenance problem. Developers that have to modify your code in the future may not realize that you intended that decision to be so focused and will start adding conditions that are not using that variable. Someone will come along and say, I want num to equal 10 if the last key sequence was 5-4-8, and tack an additional else if on the end of your block. Eventually that section will become a Gourdian knot of if...else if conditions that no one can understand. The future will hate you and bad karma will be added to your account.Use a switch statement when possible. It clearly communicates that this section of code relies on a single variable and is much more future-proof.