Computer Science

Java Switch Statement

Java Switch Statement is a control statement that allows a program to execute different actions based on different conditions. It evaluates an expression and compares it with multiple cases and executes the code block associated with the first matching case. It is a cleaner and more efficient alternative to using multiple if-else statements.

Written by Perlego with AI-assistance

12 Key excerpts on "Java Switch Statement"

  • Book cover image for: Data Structures and Program Design Using Java
    No longer available |Learn more
    . Also, a switch statement is comparatively easy to understand and debug. The general syntax of the switch statement is as follows:
    switch (choice)
    {   case constant 1:   Statements 1 ; break ;   case constant 2:   Statements 2 ; break ;   case constant 3:   Statements 3 ; break ;
      .
      .
      .  
      case constant n:   Statements n ; break ;   default:   Statements D ; }
    Figure 2.7. Switch statement flow diagram.
    A switch statement works as follows:
    • Initially, the value of the expression is compared with the case constants of the switch construct.
    • If the value of the expression and the switch statement match, then its corresponding block is executed until a break is encountered. Once a break is encountered, the control comes out of the switch statement.
    • If there is no match in the switch statements, then the set of statements of the default is executed.
    • All the values of the case constants must be unique.
    • There can be only one default statement in the entire switch statement. A default statement is optional; if it is not present and there is no match with any of the case constants, then no action takes place. The control simply jumps out of the switch statement.
    For example:
    //Write a program to demonstrate the switch case.
    import java.util.*;
    public class Switch
    {      public static void main(String[] args)      {
            Scanner src = new Scanner(System.in);         System.out.println("Enter your choice:");         int choice = src.nextInt();         switch(choice)         {              case 1:                    System.out.println("Inside First Case!");                    break;              case 2:                    System.out.println("Inside Second Case!");                    break;              case 3:
                       System.out.println("Inside Third Case!");                    break;              default:                    System.out.println("Wrong choice");         }      } } The output of the program is shown as:  

    Frequently Asked Questions

    4. Which one is better—a switch case or an else-if ladder?
  • Book cover image for: Developing Java Software
    • Russel Winder, Graham Roberts(Authors)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    In other words, this is another way of always assigning zero to a! The indentation means nothing here—it is the sequence of characters that matter not the column positioning. So whilst indentation should be indicative, there are still traps for the unwary. This is another argument for always being defensive, for always using compound statements. 20.2.2 The Switch Statement Purpose The switch statement provides multi-way selection, allowing conditional execution of one or more out of many statements depending on the value of an expression. Intention We want to choose which statement sequence to execute depending on the value of an integer, character or enumerated type expression. For example, if we have a variable holding an int in the range 1–7, we want to be able to display the name of the current day. This could be done using a series of if statements but as this kind of situation occurs relatively frequently in programs, Java provides the switch statement to package up what we want in a more convenient way. Syntax switch ( char/int/enum expression ) { case char/int/enum constant : statementSequence . . . default : statementSequence } Description The switch statement provides another way of selecting between choices. In contrast to the if statement, the switch statement allows a choice to be made between any number of statement sequences, not just two statements. The body of the switch statement must be a compound statement (i.e. a sequence of statements enclosed in braces). This compound statement actually comprises a number of labelled statement sequences, where each labelled sequence represents one choice. A labelled sequence starts with the case keyword followed by a constant value (the label), a colon and then the sequence of statements to be executed (which as always may include a compound statement, this will again be important to our defensive style).
  • Book cover image for: OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide
    • Jeanne Boyarsky, Scott Selikoff(Authors)
    • 2019(Publication Date)
    • Sybex
      (Publisher)
    switch statements.

    Statements and Blocks

    As you may recall from Chapter 2 , “Java Building Blocks,” a Java
    statement
    is a complete unit of execution in Java, terminated with a semicolon (; ). For the remainder of the chapter, we’ll be introducing you to various Java control flow statements.
    Control flow statements
    break up the flow of execution by using decision-making, looping, and branching, allowing the application to selectively execute particular segments of code.
    These statements can be applied to single expressions as well as a block of Java code. As described in Chapter 2 , a
    block
    of code in Java is a group of zero or more statements between balanced braces ({} ) and can be used anywhere a single statement is allowed. For example, the following two snippets are equivalent, with the first being a single expression and the second being a block of statements:
    // Single statement patrons++;   // Statement inside a block { patrons++; }
    A statement or block often functions as the target of a decision-making statement. For example, we can prepend the decision-making if statement to these two examples:
    // Single statement if(ticketsTaken > 1) patrons++;   // Statement inside a block if(ticketsTaken > 1) { patrons++; }
    Again, both of these code snippets are equivalent. Just remember that the target of a decision-making statement can be a single statement or block of statements. For the rest of the chapter, we will use both forms to better prepare you for what you will see on the exam.
  • Book cover image for: OCP Oracle Certified Professional Java SE 17 Developer Study Guide
    • Scott Selikoff, Jeanne Boyarsky(Authors)
    • 2022(Publication Date)
    • Sybex
      (Publisher)
    110 Chapter 3 ■ Making Decisions System.out.print(data.intValue()); else return; } Our new code is equivalent to our original and better demonstrates how the compiler was able to determine that data was in scope only when number is an Integer . Make sure you understand the way flow scoping works. In particular, it is possible to use a pattern variable outside of the if statement, but only when the compiler can definitively determine its type. Applying switch Statements What if we have a lot of possible branches or paths for a single value? For example, we might want to print a different message based on the day of the week. We could certainly accomplish this with a combination of seven if or else statements, but that tends to create code that is long, difficult to read, and often not fun to maintain: public void printDayOfWeek(int day) { if(day == 0) System.out.print(Sunday); else if(day == 1) System.out.print(Monday); else if(day == 2) System.out.print(Tuesday); else if(day == 3) System.out.print(Wednesday); ... } Luckily, Java, along with many other languages, provides a cleaner approach. In this section we present the switch statement, along with the newer switch expression for controlling program flow. The switch Statement A switch statement, as shown in Figure 3.3, is a complex decision-making structure in which a single value is evaluated and flow is redirected to the first matching branch, known as a case statement. If no such case statement is found that matches the value, an optional Applying switch Statements 111 default statement will be called. If no such default option is available, the entire switch statement will be skipped. Notice in Figure 3.3 that case values can be combined into a single case statement using commas. Because switch statements can be longer than most decision-making statements, the exam may present invalid switch syntax to see whether you are paying attention.
  • Book cover image for: Programming Fundamentals Using JAVA
    No longer available |Learn more

    Programming Fundamentals Using JAVA

    A Game Application Approach

    switch statement limits the operator used in its decision making to equality. In addition, the equality must be between:
    two String objects
    two byte , short , char , or int primitive-data types (or classes that "wrap" these data types), or
    two instances of a previously defined enumerated type (which will be discussed in Chapter 7 )
    All uses of the switch statement can be coded using an if-else statement, but not vice versa. That being said, there are times when the use of the switch statement makes our programs more readable and therefore easier to understand, modify, and maintain. It can only be used when the decision as to which statements to execute and which statements to skip is based on a choice selected from a group, or menu, of finite choices. When this is the case, the use of the switch statement is considered to be good programming practice.
    The syntax of the switch statement is depicted in Figure 4.11 . The indentation used in the figure also reflects good programming practice.
    Figure 4.11The syntax of the switch statement.
    As shown in the figure, the first line of the statement begins with the keyword switch , and the remaining lines of the statement consist of case clauses and a default clause enclosed in a set of brackets. When typing the statement, it is best to begin by typing the following required syntax and then filling in the remainder of the statement’s first line and the case and default clauses that are appropriate to the particular use of the statement.
    switch ( )
    { }
    Referring to Figure 4.11 , the three most common (and difficult to discover) syntax errors made when coding a switch statement are:
    1. neglecting to code the open and close parentheses after the keyword switch
    2. coding a semicolon after the close parenthesis on the first line of the statement
    3. neglecting to code the colon (not semicolon) after the choiceValue1 , or choiceValue2 ... or after the keyword default
    The entity enclosed in the parentheses after the keyword switch is referred to as the choice expression . The choice expression must be a variable whose type is one of the allowable types previously mentioned (e.g., a String
  • Book cover image for: Introduction to Programming
    No longer available |Learn more

    Introduction to Programming

    Learn to program in Java with data structures, algorithms, and logic

    Control Flow Statements

    This chapter describes one particular kind of Java statement
    , called control statements, which allow the building of a program flow according to the logic of the implemented algorithm, which includes selection statements, iteration statements, branching statements, and exception handling statements.
    In this chapter, we will cover the following topics:
    • What is a control flow?
    • Selection statements: if, if....else, switch...case
    • Iteration statements: for, while, do...while
    • Branching statements: break, continue, return
    • Exception handling statements: try...catch...finally, throw, assert
    • Exercise – Infinite loop
    Passage contains an image

    What is a control flow?

    A Java program is a sequence of statements that can be executed and produce some data or/and initiate some actions. To make the program more generic, some statements are executed conditionally, based on the result of an expression
    evaluation. Such statements are called control flow statements because, in computer science, control flow (or flow of control) is the order in which individual statements are executed or evaluated.
    By convention, they are divided into four groups: selection statements, iteration statements, branching statements, and exception handling statements. In the following sections, we will use the term block, which means a sequence of statements enclosed in braces. Here is an example: { x = 42; y = method(7, x); System.out.println("Example"); } A block can also include control statements – a doll inside a doll, inside a doll, and so on.
    Passage contains an image

    Selection statements

    The control flow statements of the selection statements group are based on an expression evaluation. For example, here is one possible format: if(expression) do something. Or, another possible format: if(expression) {do something} else {do something else}.
    The expression may return a boolean value (as in the previous examples) or a specific value that can be compared with a constant. In the latter case, the selection statement has the format of a switch statement, which executes the statement or block that is associated with a particular constant value.
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    From Problem Analysis to Program Design

    The value of the expression is then used to choose and perform the actions specified in the statements that follow the reserved word case. Recall that in a syntax, shading indicates an optional part of the definition. Although it need not be, the expression is usually an identifier. Whether it is an identifier or an expression, the value can be only integral. The expression is some- times called the selector. Its value determines which statement is selected for execu- tion. A particular case value should appear only once. One or more statements may follow a case label, so you do not need to use braces to turn multiple statements into a single compound statement. The break statement may or may not appear after each statement. The general diagram to show the syntax of the switch statement is not straightforward because following a case label a statement and/or a break state- ment may or may not appear. Keeping these in mind, Figure 4-4 shows the flow of Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 228 | Chapter 4: Control Structures I (Selection) execution of a switch statement. Note that in the figure following a case value, the box containing statement and/or the box containing break may or may not appear. Following the figure, we give the general rules that a switch statement follows. FIGURE 4-4 switch statement expression statements1 break break break statements2 statementsn statements case value1 case value2 case valuen default false false false false true true true The switch statement executes according to the following rules: 1.
  • Book cover image for: C# Programming
    eBook - PDF

    C# Programming

    From Problem Analysis to Program Design

    Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 290 | Chapter 5: Making Decisions The curly braces are required with a switch statement. That is different from an if statement in which they are only required when more than one statement makes up the true statement or the false statement body. A syntax error is generated if you fail to use curly braces before the first case and at the end of the last case with the switch statement. The last statement for each case and the default is a jump statement . The break keyword is used for this jump. Other types of jump statements are covered in the next chapter. When break is encountered, control transfers outside of the switch statement. Unlike other languages that allow you to leave off a break and fall through executing code from more than one case , C# requires the break for any case that has an exe-cutable statement(s). You cannot program a switch statement in C# to fall through and execute the code for multiple cases. C# also differs from some other languages in that it requires that a break be included with the default statement. If you do not have a break with a default statement, a syntax error is issued. Many languages do not require the break on the last case because the default is the last statement. A natural fallout occurs. Switch statements are often used to associate longer text with coded values as is illus-trated in Example 5-22. Instead of asking the user to enter the full name for the day of the week, they could enter a number. The switch statement would then be used to display the related value.
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    Program Design Including Data Structures

    Recall that in a syntax, shading indicates an optional part of the definition. Although it need not be, the expression is usually an identifier. Whether it is an identifier or an expression, the value can be only integral. The expression is some-times called the selector . Its value determines which statement is selected for execu-tion. A particular case value should appear only once. One or more statements may follow a case label, so you do not need to use braces to turn multiple statements into a single compound statement. The break statement may or may not appear after each statement. The general diagram to show the syntax of the switch statement is not straightforward because following a case label a statement and/or a break state-ment may or may not appear. Keeping these in mind, Figure 4-4 shows the flow of Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 228 | Chapter 4: Control Structures I (Selection) execution of a switch statement. Note that in the figure following a case value, the box containing statement and/or the box containing break may or may not appear. Following the figure, we give the general rules that a switch statement follows. FIGURE 4-4 switch statement expression statements1 break break break statements2 statementsn statements case value1 case value2 case valuen default false false false false true true true The switch statement executes according to the following rules: 1. When the value of the expression is matched against a case value (also called a label), the statements execute until either a break statement is found or the end of the switch structure is reached. 2. If the value of the expression does not match any of the case values, the statements following the default label execute. If the switch structure has no default label and if the value of the expression does not match any of the case values, the action of the switch statement is null.
  • Book cover image for: Learn C Programming from Scratch
    eBook - ePub

    Learn C Programming from Scratch

    A step-by-step methodology with problem solving approach (English Edition)

    The values are the forms that the expression could take, forming the case of a switch construct. The relevant block of code will be run if the expression matches any cases. The default block’s statements will be executed if none of the case values matches the expression.
    The evaluation of the phrase and subsequent comparison with the case values are how the switch construct operates. When a match is found, the case’s code is run after which the switch statement should be terminated using the break statement. Please refer to the following figure:
    Figure 3.2: Selection/ switch logic
    The control will pass to the next case if no break statement is found, and the following code blocks will likewise be run until a break statement is found.
    The switch statement is frequently employed for evaluating a discrete set of values. It can be used, for instance, to manage menu selections, process several options, or carry out computations based on various inputs.
    Syntax: The syntax for a switch statement in C programming language is as follows:
    switch(expression) { case constant-expression:
    statement(s);
    break; case constant-expression: statement(s); break; // We can have any number of case statements */ default: statement(s); } The following rules apply to a switch statement:
    • The switch statement’s phrase must be of an integral type. Enumerated types and integer types like int , char , short , and long are included.
    • The switch statement’s case labels must all be constant expressions and cannot be a run-time-evaluable variable or expression.
    • Within the switch statement, each case label must be different. The use of duplicate case labels is prohibited.
    • The default case serves as a general-purpose case and is optional. It is executed when none of the case labels match the expression’s value. Although it can occur anywhere in the switch statement, the default case is usually put at the conclusion.
    • The relevant code block and a colon (: ) must come after the case labels. Each case label’s corresponding code block may include numerous statements.
    • A break statement ends the switch statement once a case is matched and processed . The control flow will move on to the next case without the break
  • Book cover image for: Java All-in-One For Dummies
    • Doug Lowe(Author)
    • 2023(Publication Date)
    • For Dummies
      (Publisher)
    [ default: statements; break; ]... } The expression must evaluate to an int, short, byte, char, String, or enum. It can’t be a long or a floating-point type. You can code as many case groups as you want or need. Each group begins with the word case, followed by a constant (usually, a simple numeric or String literal) and a colon. Then you code one or more statements that you want executed if the value of the switch expression equals the constant. The last line of each case group is an optional break statement, which causes the entire switch statement to end. The default group, which is optional, is like a catch-all case group. Its state- ments are executed only if none of the previous case constants match the switch expression. Note that the case groups are not true blocks marked with braces. Instead, each case group begins with the case keyword and ends with the case keyword that starts the next case group. All the case groups together, however, are defined as a block marked with a set of braces. 182 BOOK 2 Programming Basics The last statement in each case group usually is a break statement. A break statement causes control to skip to the end of the switch statement. If you omit the break statement, control falls through to the next case group. Accidentally leaving out break statements is the most common cause of trouble with the switch statement. Viewing a boring switch example, complete with flowchart Okay, the autonomous vehicle error decoder was kind of fun. Here’s a more down- to-earth example. Suppose that you need to set a commission rate based on a sales class represented by an integer (1, 2, or 3) according to this table: Class Commission Rate 1 2% 2 3.5% 3 5% Any other value 0% You could do this with the following switch statement: double commissionRate; switch (salesClass) { case 1: commissionRate = 0.02; break; case 2: commissionRate = 0.035; break; case 3: commissionRate = 0.05; break; default: commissionRate = 0.0; break; }
  • Book cover image for: Java Foundations
    • Todd Greanier(Author)
    • 2006(Publication Date)
    • Sybex
      (Publisher)
    4373book.fm Page 96 Tuesday, July 13, 2004 3:44 PM Flow Control 97 The number passed to System.exit() is not meant to be used for error handling. There is no way to recover from this method call. If you exit the virtual machine, no more processing is possible. Later in this chapter, you learn how to handle logic errors in your code. The switch and case Statements Another way to perform decision-oriented flow control is with the switch state-ment. While if/else statements are used to process true and false results, the switch statement is used to process integer results. This statement is used in con-junction with a series of case statements. The switch statement has a condi-tional expression associated with it, and each case statement is bound to one of the possible values for that expression. Each case statement is followed by one or more statements that are executed in order. The switch statement can process only four primitive types: byte , short , char , and int . No other types are allowed for evaluation in a switch statement. Although char may not seem to be an integer, it is. The value it actually holds is the Unicode value, which is a 16-bit integer value. It is represented in code nor-mally as an actual character, of course. Some languages (notably Visual Basic) allow you to associate strings with switch statements. However, Java does not allow anything other than integer types. This is a good time to explore a more complex piece of code. The SwitchDemo class that follows is the most elaborate class you have seen so far in this book. The concept of this code is that you select one of four arithmetic operations (addition, subtraction, multiplication, or division) and provide two operands to work with. When you execute this code, you must pass three command-line arguments. The first argument is the code for the arithmetic operation that you want to perform.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.