Java – are you sure you know how switch case works?

Three years ago, back when I was preparing for the Java programmer certification, I used to think I had a pretty good insight knowledge of my programming language. Although I realized that I wasn’t absolutely wrong, there were some things that I got surprised. One of them was the way that switch case really works. So, for instance, take a look at the following snippet, and try to predict what will be the result of executing the code (don’t peek at the solution without trying first the resolution of the code):

public class SwitchCaseTest {

  public static void main(String[] args) {
    int existingCase = 0;
    System.out.println("i = " + existingCase);
    doWithDefaultAtEnd(existingCase);
    doWithDefaultAtStart(existingCase);

    System.out.println();

    int nonExistingCase = 2;
    System.out.println("i = " + nonExistingCase);
    doWithDefaultAtEnd(nonExistingCase);
    doWithDefaultAtStart(nonExistingCase);
  }

  private static void doWithDefaultAtEnd(int i) {
    switch (i) {
      case 0:
        System.out.println("0");
        break;
      case 1:
        System.out.println("1");
        break;
      default:
        System.out.println("default@end");
    }
  }

  private static void doWithDefaultAtStart(int i) {
    switch (i) {
      default:
        System.out.println("default@start");
      case 0:
        System.out.println("0");
        break;
      case 1:
        System.out.println("1");
        break;
    }
  }
}

As you might have discovered by now, the basic difference resides in the fact of the positioning of the default case statement. When the default statement is at the beginning of method for which it gets a parameter that is not matched in any of the other case statements, what will happen? That was my doubt when I was studying Java for the certification… what about you? Do you know the answer? 🙂

Next, there’s the results of the execution of the previous class… was it what you were expecting? If so, congratulations. If not, don’t be sad because I’m pretty sure a lot of people (even those experienced in Java) would fail this, if they were asked… 😉

i = 0
0
0

i = 2
default@end
default@start
0
Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s