Start learning with our library of video tutorials taught by experts. Get started

Java Essential Training

Using the switch statement


From:

Java Essential Training

with David Gassner

Video: Using the switch statement

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.
Expand all | Collapse all
  1. 10m 8s
    1. Welcome
      1m 3s
    2. Is this course for you?
      5m 35s
    3. Using the exercise files
      3m 30s
  2. 31m 24s
    1. The history of Java
      5m 19s
    2. Java compilation and syntax
      8m 54s
    3. Understanding the principles of Java
      8m 28s
    4. Choosing a development environment
      8m 43s
  3. 19m 5s
    1. Installing Java on Windows
      6m 42s
    2. Installing Eclipse on Windows
      3m 19s
    3. Exploring Java on Mac OS X Leopard and Snow Leopard
      2m 27s
    4. Installing Java on Mac OS X Lion
      3m 27s
    5. Installing Eclipse on Mac OS X
      3m 10s
  4. 46m 10s
    1. Creating a Hello World application
      11m 7s
    2. Exploring the Eclipse IDE
      8m 55s
    3. Compiling and running from the command line
      8m 2s
    4. Passing arguments to the application
      8m 17s
    5. Using the Java API documentation
      4m 5s
    6. Memory management and garbage collection
      5m 44s
  5. 58m 57s
    1. Everything is an object
      5m 59s
    2. Declaring and initializing variables
      9m 15s
    3. Working with numbers
      8m 32s
    4. Converting numeric values
      6m 40s
    5. Understanding operators
      7m 58s
    6. Working with character values
      5m 14s
    7. Working with boolean values
      5m 13s
    8. Outputting primitive values as strings
      5m 33s
    9. Creating a simple calculator application
      4m 33s
  6. 53m 40s
    1. Writing conditional code
      5m 35s
    2. Using the switch statement
      8m 50s
    3. Repeating code blocks with loops
      7m 35s
    4. Creating reusable code with methods
      6m 31s
    5. Declaring methods with arguments
      5m 41s
    6. Overloading method names with different signatures
      5m 53s
    7. Passing arguments by reference or by value
      5m 35s
    8. Creating a more complex calculator application
      8m 0s
  7. 20m 30s
    1. Using the String class
      5m 44s
    2. Building strings with StringBuilder
      3m 34s
    3. Parsing string values
      3m 19s
    4. Working with date values
      7m 53s
  8. 20m 44s
    1. Understanding compile-time vs. runtime errors
      4m 5s
    2. Handling exceptions with try/catch
      4m 55s
    3. Throwing exceptions in methods
      2m 50s
    4. Using the debugger
      8m 54s
  9. 32m 22s
    1. Using simple arrays
      4m 47s
    2. Using two-dimensional arrays
      6m 17s
    3. Managing resizable arrays with ArrayList
      7m 14s
    4. Managing unordered data with HashMap
      6m 5s
    5. Looping through collections with iterators
      7m 59s
  10. 52m 2s
    1. Understanding encapsulation
      5m 59s
    2. Creating and instantiating custom classes
      8m 8s
    3. Organizing classes with packages
      6m 47s
    4. Creating and using instance methods
      6m 52s
    5. Storing data in instance variables
      6m 56s
    6. Using constructor methods
      5m 40s
    7. Managing instance data with getter and setter methods
      8m 26s
    8. Using class variables and Enum classes
      3m 14s
  11. 41m 15s
    1. Understanding inheritance and polymorphism
      9m 12s
    2. Extending custom classes
      9m 1s
    3. Overriding superclass methods
      3m 8s
    4. Casting subclass objects
      5m 3s
    5. Understanding interfaces and implementing classes
      4m 2s
    6. Creating your own interfaces
      4m 14s
    7. Using abstract classes and methods
      6m 35s
  12. 32m 17s
    1. Managing files with the core class library
      7m 46s
    2. Managing files with Apache Commons FileUtils
      7m 32s
    3. Reading a text file from a networked resource
      7m 52s
    4. Parsing an XML file with DOM
      9m 7s
  13. 17m 39s
    1. Creating your own JAR files
      4m 54s
    2. Understanding the classpath
      5m 2s
    3. Documenting code with Javadoc
      7m 43s
  14. 47s
    1. Goodbye
      47s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Java Essential Training
7h 17m Beginner Dec 14, 2011

Viewers: in countries Watching now:

Join author David Gassner as he explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more. This course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts.

Topics include:
  • Understanding the history and principles of Java
  • Installing Eclipse and Java
  • Compiling and running from the command line
  • Managing memory and performing garbage collection
  • Declaring and initializing variables
  • Writing conditional code
  • Building and parsing strings
  • Debugging and exception handling
  • Using simple arrays
  • Creating custom classes
  • Working with encapsulation, inheritance, and polymorphism
  • Managing files
  • Documenting code with Javadocs
Subjects:
Developer Programming Languages
Software:
Android Java Eclipse
Author:
David Gassner

Using the switch statement

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.

I'm going to comment out each of these break statements, so you can see the behavior. I'll place the cursor on the line and then press Ctrl+/ on Windows or Command+/ on Mac, and that will add double slash comments to each of these lines. Now I'll Save my changes, Run the application, and I'll type the number 2 and I get not just the month as February, but I also get all of the other code executing for the rest of the switch statement. This code model works the same as it does in JavaScript, C++, and other C-Style languages.

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.

There are currently no FAQs about Java Essential Training.

Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Java Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked