Switch default not at the end

Learned something new last week looking over a programming contest test. Turns out that default doesn’t have to be the last condition in a switch case statement. At least, not in Java.

I knew you could leave it off. But everywhere I’ve ever seen a switch case statement that included default, default was the last condition.

Going off of memory, this is pretty close to the problem from the test. It asked for output, and “No output, error” was an option.

Submit

int x = 3; switch (x) { case 2: System.out.println("2"); break; default: System.out.println("default"); break; case 3: System.out.println("3"); break; case 4: System.out.println("4"); break; }
>

If you run this it’ll print out 3 even though the default comes before it. If you change x to something other than 2, 3 or 4 it’ll print out default.

Every switch statement I’ve ever written has default at the end. Now though I’m wondering if it makes more sense for it to come first.

Submit

int x = 3; switch (x) { default: System.out.println("default"); break; case 2: System.out.println("2"); break; case 3: System.out.println("3"); break; case 4: System.out.println("4"); break; }
>

That seems a little more readable to me, but I think the fact that default isn’t where everyone would expect it to be makes it worse. I’d never put it in the middle though. That’s just painful.

Either way, it was an interesting problem and lead to a good discussion in class. Pretty much everyone, including me, missed the problem.

CompSci.rocks Newsletter

Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?

Leave a Reply

Your email address will not be published. Required fields are marked *