Site updates
Testing New System now...

Switch statements

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
	    case 1 :

	    case 2 :

	    case 3 :

	    case 4 :

	    default :  Notice this is " default ", and not " case default : "
		System.out.println("Something else");


If you have troubles compiling, you may want to read these articles:

Statement not reached
'case' or 'default' outside switch statement

And, because I'm in such a generous mood, there's even some downloads, of the program that wasn't called, after I realised even my sense of humour isn't that bad.

Download casedemo.class
NOTE: The Java section is mostly in maintenence mode. I don't have time to work on it right now. Errors will be corrected if pointed out, but they are not actively being searched for. Newer site features, like alternate stylesheets, may cause problems with these pages.