Switch Statement in Java: Example & Syntax

Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

The switch statement in Java is an effective way to branch a program based on specific conditions, and can be used in place of writing an extended if statement. In this lesson, we'll leran the syntax of the command and look at a few examples.

The Switch Statement

Tracks

Think of the Java switch statement in terms of an old-time railroad switch operator. There may be two or twenty tracks the split from one: as a train approaches, the engineer yells out a number or statement. The switch operator then engages the switch and the train goes down the correct track.

In Java, the statement evaluates the expression - the engineer's command - and then goes to a position within the switch statement based on that value. However, only certain data types are allowed to be evaluated: int, short, byte, char, or String. Doubles or floats are not allowed: these numbers can be long and not exactly very precise - is it 1.1 or 1.1000000000000000000000000000000003478998?

The go-to positions, the tracks if you will, are called the case labels and they contain the constant value (which must be the same data type as the switch expression).

A default keyword is used at the end, to capture any values that don't match any of the given options. That way the train goes down a specified track, and doesn't derail.

Syntax and Examples

Let's first look at the syntax of a switch statement, after which we'll study some examples.

Syntax

The syntax for the switch statement is:

switch(expression) {
  case constant1:
   statement 1;
   break;
   //... more cases as needed ...
  default;
   statements;
  }

This code has the same effect as a nested if statement. But switch is more efficient since the computer looks at only one expression, then hops to the case within the statement. With a nested if, the computer has to go through each statement, which increases computational time (which we should try to keep down).

The break statements are not required, but are recommended in each case statement. These tell the computer to skip to the end of the switch statement.

Example: Menu Option

Let's take a look at an example. In the following code, we ask for a user to enter a number and then process a specific set of instructions based on that number. If they hit a number we haven't accounted for, the program skips to the default option and stops.

public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  System.out.println("Enter a Number: ");
  int myAnswer = Integer.parseInt(scanner.next());
  switch(myAnswer) {
   case 1:
    System.out.println("You entered 1!");
    break;
   case 2:
    System.out.println("You entered 2!");
    break;
   case 3:
    System.out.println("Are we there yet?");
    break;
   default:
    System.out.println("I try to think but nothing happens");
  }
}

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support