Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
There are many times in applications where you have a variable and you want to check that variable against a set of finite values. You could model this code using an if statement, and a whole set of else-ifs or you could do it a little more elegantly with a switch. I'll show you how to use a switch in Java in this project, Switch, which you can find in Chapter 5 of the Exercise Files. The project has a few different classes, I'm working with the SwitchWithInts, this application already has the getInput method that I've used in a previous video, it accepts a value typed in at the command line and returns a String.
I'll start in this application by receiving a value and converting it to an integer. I'll place the cursor inside the main method and declare a String named input, then I'll fill in its value by calling the getInput method, I'll pass a prompt into the getInput method of Enter a number between 1 and 12: Next I'll convert the String to an integer, I'll declare an int variable called month and I'll convert it using the Integer class's parseInt (input) method, I'll pass in the input, and now I should have an integer to work with.
Now, I'm doing this because in Java up through version 6.0 you can use the switch statement only with integers, shorts, bytes, and a special class called Enums. In Java 7.0 you can actually use switches with strings, but I have my copy of Eclipse setup on Java 6.0 right now, so I'll stick with what works with that version. The next step is to create the structure of a switch statement, just as with if statement Eclipse will help you, type the word switch and press Ctrl+Space and then press Enter or Return to choose the first item in the list and that creates the basic structure.
The switch syntax looks like this, after the keyword switch you put in a pair of parenthesis and then you pass in the variable that you're evaluating. I'm evaluating the variable month. Next you have one or more case statements, each case statement takes a value, the value must be an integer or an enumeration or Enum, I'll describe those later, but for now, I'm going to use the literal value of 1. Then after the case statement, but before the word break, you put in your executable code, this code will only execute if the value in the case statement matches the variable in the switch command.
I'll output a bit of text System.out.println, and I will output ("The month is January"); so I making an equivalence between the number 1 and the month January. Now, I'm going to copy and paste this case statement, including the three lines from case to break, I'll copy and then paste twice, close up the code a bit, I'll change the values I'm evaluating to 2 and 3, and I'll change their equivalent months to February and March. So my application is now at a point where it should work correctly.
I'll run the application, in the console view I'll click in and then type the number 1, and I get the month as January. I'll run it again and type in 2 pressing Enter or Return and I get the month as February. And finally, I'll test a value that's not one of those numbers like 6, and press Enter or Return and nothing happens. Well, that's because I haven't filled in this bit of code, the default. The keyword default means execute this code if none of the previous cases return true, so here I'll put in System.out. println and then I'll output the String ("You chose another month").
I'll Run and once again I'll type in 6, and this time I get the default behavior. So that's the basic of a switch statement. Let's also talk about the break keyword. The break keyword is used to breakout of a code block in Java. Right now our code block is everything from this opening brace to this closing brace. When you say break, it means jump to the end of the code block. You need break statement in cases, because if you don't have them, the code will just keep executing throughout the rest of the switch statement.
The rules are straight forward as soon as you get a match between the variable and the value in a case statement the code will start executing and it would keep executing for the rest of the code block. If you don't want that to happen, and you really never do, then you have to put those break statements into each case. So I'm going to get rid of those comments, all I need to do is move the cursor to each line and press Ctrl+/ or Command +/ and now the code is back in its working state. In Java, through version 6.0, you can use switch statement for integers or for a special class called Enums, and again, as I mentioned before, in Java 7.0 you can use switch statements on Strings, but I'm working in Java 6.0 here, so I'm going to stick to integers and Enums.
Let's take a look at how Enums work. An Enum is short for Enumeration, it's a way of providing a set of possible values, in older version of the Java, previous to version 5.0, you had to create your own enumerations using a particular code model, but now they're native to language and have been for the last couple of versions. Here is how you create enumeration. I'll go to my default package in the project and choose New Enum. An Enum is a kind of a class, so you have a very similar wizard as for a new class, but without all the options.
I'll give this Enum a type of Month, I won't use a package I'll just ignore that warning that the use of the default package is discouraged, and I'll click Finish. Now within the Enum I'm going to type in the names of the constants that I want to use, JANUARY, FEBRUARY, MARCH, notice that after I saved the file Eclipse automatically evaluates and recognizes that those are constants of the Enum class and it color codes them appropriately. Now I'll switch to the application SwitchWithEnums.java, this is a shortened version of that previous application; it has an integer variable with the value of 1.
I'm going to copy out that version of the month declaration and I'm going to change it to an instance of the month class or a month Enum that looks like this. When I type in Month.Eclipse gives me a listing of the possible values and you'll see that the values that I put into the Enum class, JANUARY, FEBRUARY, and MARCH, are proposed. I'll choose FEBRUARY. Now I'm going to change my switch statement a bit, the switch statement itself stays the same, because I reused the variable name month, but now, instead of evaluating integers, I'm evaluating constants of the Enum, and it will look like this, case JANUARY, notice that within the switch statement I don't have to use the month dot prefix and I'll change the string from the month as JANUARY to ("It's the first month").
I'll change 2 to FEBRUARY and I'm just pressing Ctrl+Space to auto fill that value and I'll change this String to ( It's the second month) and I'll change 3 to MARCH and the output String to ("It's the third month"). The advantage of using an enumeration is that you can explicitly say these are the only possible values, when you say something as an integer, you're not limiting yourself to 1 through 12, you have literally millions of possibilities. The advantage of the Enum is that you're limiting the possibilities, and making it very clear what's possible in this situation.
So now I'll Run the application and I get (It's the second month). I'll talk more about enumeration at a later point of the course, but you can see how useful they might be for various situations in your applications. Finally, I'll show you what the code would look like if Strings were supported in the switch statement. As I've mentioned, I can't do this right now, because I'm working in Java 6.0, but if you're working in Java 7.0, one of the improvements to the language is the ability to use Strings in switch statement, and this is what the code would look like. The purpose of switch statement is to make conditional logic a little more elegant and to prevent the need from multiple else-if statements that make the code harder to read.
Get unlimited access to all courses for just $25/month.Become a member