Switch statements can be used when you are selecting from a known list of alternatives. It provides a more convinient alternative to multiple IF statements. One or more cases are stated, plus a default to catch anything that didn't fit into the other cases.
Depending on the situation, it may be more useful to use the default statement to check for errors. It should only be used for normal processing when you are 100% sure all inputs will be valid.
The values for the case statements must be constants. If you are using a named constant, such as MILK_CHOCOLATE, it helps to put a space between the constant name and the colon, as sometimes the compiler rejects it if you don't.
int thing = (int)(Math.random()*5);This produces a random number from 0 to 4 switch (thing) { case 0 : The 0 here is a possible value of thing System.out.println("Zero"); break; case 1 : System.out.println("One"); break; case 2 : System.out.println("Two"); break; case 3 : System.out.println("Three"); break; case 4 : System.out.println("Four"); break; default : Notice this is " default ", and not " case default : " System.out.println("Something else"); break; }
If you have troubles compiling, you may want to read these articles:
And, because I'm in such a generous mood, there's even some downloads, of the program that wasn't called testcase.java, after I realised even my sense of humour isn't that bad.