The Java switch Statement

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Intro to CS – Honors I Control Flow: Branches GEORGIOS PORTOKALIDIS
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
CIS162AD - C# Decision Statements 04_decisions.ppt.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Flow of Control Part 1: Selection
Decision Making Selection structures (if....else and switch/case)
Lecture 4 Control Structures MIT – AITI What are Control Structures? Control structures are a way to alter the natural sequence of execution in.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Switch Statements Comparing Exact Values. The Switch Statement: Syntax The switch statement provides another way to decide which statement to execute.
Conditional Statement Chapter 8. Conditional Statements Are statements that check an expression then may or may not execute a statement or group of statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Decisions. Three Forms of Decision Making in Java if statements (test a boolean expression) switch statements (test an integer expression) conditional.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Quiz 1 Exam 1 Next Monday. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) System.out.println(“You have an A!” ); else System.out.println(“You.
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
The for Statement A most versatile loop
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Lecture 4 CS140 Dick Steflik. Reading Keyboard Input Import java.util.Scanner – A simple text scanner which can parse primitive types and strings using.
C++ LANGUAGE MULTIPLE CHOICE QUESTION
Java Programming Fifth Edition
Week 3 - Friday CS222.
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
More important details More fun Part 3
Chapter 4: Making Decisions.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
EGR 2261 Unit 4 Control Structures I: Selection
Flow of Control.
Chapter 3 Branching Statements
Boolean Expressions and If
DKT121: Fundamental of Computer Programming
Chapter 4: Making Decisions.
Conditionals & Boolean Expressions
Java Programming: Guided Learning with Early Objects
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE
Control Structures – Selection
Starting JavaProgramming
Concepts From Alice Switching to Java Copyright © Curt Hill.
Selection (if-then-else)
The most important decision statement
A Different Kind of Variable
Chapter 4: Control Structures I (Selection)
Conditionals.
CprE 185: Intro to Problem Solving (using C)
Week 3 – Program Control Structure
Program Flow.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Controlling Program Flow
Lecture 3 More on Flow Control, More on Functions,
The IF Revisited A few more things Copyright © Curt Hill.
CprE 185: Intro to Problem Solving (using C)
Presentation transcript:

The Java switch Statement A multi-path decision statement Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Flow of Control in Java Recall the flow statements in Java: Decisions If Switch Case Loops for while do Break Here we consider the switch Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Why? There are times when we would use the following type of nested if if(a == 2) x = 5; else if(a == 4) { x = 12 * y; … } else if(a == 8) {…} else if(a == 12) {…} else System.out.println(“Error”); Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill General Form of This Each if has a similar condition One variable compared with a constant Comparison is always equality The Then statement does something The Else statement does another if There is only one variable and one comparison in all the ifs Generally such a construction needs a switch-case not an if Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill If and Switch An if is a decision of one path out of two A switch is a decision of one path out of many An if is based on a boolean May only have two values A switch is based on an int, char, enumeration May have many values Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill General Form of Switch switch (integral expression) { case con1: many statements break; case con2: many statements break; case con3: many statements break; … } Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Notes switch, case and break are reserved words The parenthesized expression is evaluated to obtain a value This value chooses the path The type of the value must be an integer, character, byte or enumeration May not be floating point or any object The case indicates a path Must be followed by a constant The constant value following the case must match the type of the expression Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Example switch (credit_hours / 32) { case 0: standing = “freshman”; break; case 1: standing = “sophomore”; case 2: standing = “junior”; case 3: standing = “senior”; } Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill More Notes There is only one set of braces which surrounds all the cases The path starts with a case and ends with a break Multiple cases allow for multiple ways to identify a path The cases do not have to be in any particular order Duplicate cases are not allowed Compiler actually checks for this Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Multiple case example switch (grade) { case ‘a’: case ‘A’: points = 4 * credit_hours; break; case ‘b’: case ‘B’: points = 3 * credit_hours; … } Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Missing Path What happens if the switch expression does not match any case label? Equivalent to the correct case followed by a break It does nothing The default label allows a catch all case Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Example Revisited switch (credit_hours / 32) { case 0: standing = “freshman”; break; … case 3: standing = “senior”; default: standing = “unknown”; System.out.println(“Error”); } Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill default default is a reserved word The default label acts like a case label with out case or specifying a value It catches any value not explicitly mentioned in a case It is customarily last, but does not have to be Leaving it out is the same as doing nothing for all the unmentioned cases Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill The Break Statement The break has the effect of leaving a switch or loop The last path does not need a break A return will also work since it leaves the entire method not just the switch It is not required, but leaving it out makes for interesting flow Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Leaving out a break If a break is left out, execution will drop into the next part Leaving out the last break is not a problem since there is no next part Consider the following example Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Omitted break example switch (val) { case 5: x += 5; case 12: x += 8; y = 2; break; case 6: y = 4; } If val is 5, x will have 13 added to it and y will be set to 2. All the effect of val == 12 is also executed for x == 5. Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Omitted break notes This feature, inherited from C, is both good and bad It is somewhat good in that it allows an economy of code Very few switches actually use this feature It is usually bad because we seldom want it but the compiler never gives an error when a break is left out Copyright © 2004-2017 - Curt Hill

Equivalence of if and switch We have already seen an if doing what a switch can do The reverse is also true: switch(b>c){ case true: …. break; case false: …. break; } Always use what is more natural Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Common mistakes We cannot use objects for the case expression or labels We cannot use floating point values (float or double) for the expression or case labels There are problems with floating point equality Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Java 7 Starting in Java 7 a string may be used Internally it converts into a sequence of nested if statements It is case sensitive Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Example int dayofweek; String day = scan.next(); switch (day) { case “Sunday”: dayofweek = 0; break; … case “Saturday”: dayofweek = 6; default: System.out.println(“Error”); } Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Nope! switch(yertle){ ... switch(real){ case 2.1: ... } Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Uses switch is much less used than an if Just not as much need Often used to decode an integer or enumeration into a string Month number into a name Used to select different actions for these as well Often used for a menu in console programs Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Ranges Similar statements may be able to handle a range of values, but not this one If the values between 1 and 5 inclusive are to use the same path then five case constructs are needed The only easy range is the default construct Copyright © 2004-2017 - Curt Hill

Copyright © 2004-2017 - Curt Hill Finally The if chooses one of two paths, but the switch chooses one of many paths The new reserved words are: switch case default Copyright © 2004-2017 - Curt Hill