SlideShare a Scribd company logo
1 of 9
Language | Industrial Training | Digital Marketing | Web Technology | Testing+ | Database | Networking | Mobile
Application | ERP | Graphic | Big Data | Cloud Computing
Call us:
70-70-90-50-90
www.ducatindia.com
Apply Now
Switch Case Statement
When a value requires different actions for a fixed set of values, the if might get more complex, the more the
set of values increases. In this case the more suitable statement is the switch statement.
Syntax
switch ([onvar]) {
case [option]:
[statement;]
break;
…
default:
[statement;]
}
The terms in square brackets are detailed in the following list.
• [onvar] is the variable that is tested against the case statements to select a statement. It can be of any primitive type,
enumerations and starting with Java 7, String. Clearly the switch statement is not limited by conditions evaluated to
boolean results, which allows for a lot of flexibility.
• case [option] is a value the variable is matched upon to make a decision regarding the statement to execute. A case as
the keyword states.
• [statement] is a statement or a groups of statements to execute when [onvar] == [option]. Considering that there is no
else branch, we have to make sure that only the statement(s) corresponding to the first match is executed, which is
where the break; statement comes in. The break statement stops the current execution path and moves the execution
point to the next statement outside the statement that contains it. I’ll cover it later in the chapter. Without it, after the
first match, all subsequent cases are traversed, and statements corresponding to them are executed.
• So, if we execute the preceding program and we provide number 7 as an argument, the text Summer is printed. But if
the break statements for case 7 and 8 are commented, the output changes to Autumn.
• default [statement;] is a statement that is executed when no match on a case has been found, the default case does not
need a break statement. If the previous program is run with any number outside the [1-12] interval, Error is printed
because the default statement is executed.
• Now that you understand how switch works, let’s look at how we can reduce the previous statement. The month
example is suitable here, because it can further be modified to show how the switch statement can be simplified,
when a single statement should be executed for multiple cases. In our code, writing each assignment statement three
times is a little redundant. switch can be written in a different way to avoid that by grouping the cases.
Example
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=200;
//Switch expression
switch(number){
//Case statements
case 100: System.out.println(“100”);
break;
case 200: System.out.println(“200”);
break;
case 300: System.out.println(“300”);
break;
//Default case statement
default:System.out.println(“Not in 100, 200 or 300”);
}
}
}
Output
200
Flowchart of Switch Statement
Example
public class SwitchDayExample {
public static void main(String[] args) {
int day=7;
String dayString=””;
switch(day){
case 1: dayString=”1 – Monday”;
break;
case 2: dayString=”2 – Teusday”;
break;
case 3: dayString=”3 – Wednesday”;
break;
case 4: dayString=”4 – Thursday”;
break;
case 5: dayString=”5 – Friday”;
break;
case 6: dayString=”6 – Saturday”;
break;
case 7: dayString=”7 – Sunday”;
break;
default:System.out.println(“Sunday close”);
}
System.out.println(dayString);
}
}
Output
7 – Sunday
Call us:
70-70-90-50-90
www.ducatindia.com

More Related Content

Similar to Switch Case Statement

Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questions
Dr P Deepak
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 

Similar to Switch Case Statement (20)

ASSIGNMENT STATEMENTS AND
ASSIGNMENT STATEMENTS ANDASSIGNMENT STATEMENTS AND
ASSIGNMENT STATEMENTS AND
 
22 Jop Oct 08
22 Jop Oct 0822 Jop Oct 08
22 Jop Oct 08
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrols
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlan
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Building high productivity applications
Building high productivity applicationsBuilding high productivity applications
Building high productivity applications
 
Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questions
 
Base sas interview questions
Base sas interview questionsBase sas interview questions
Base sas interview questions
 
Data services-functions
Data services-functionsData services-functions
Data services-functions
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
Final requirement
Final requirementFinal requirement
Final requirement
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
 
vb.net.pdf
vb.net.pdfvb.net.pdf
vb.net.pdf
 
Sorted
SortedSorted
Sorted
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
 
Conditional Statement - Switch Case.pptx
Conditional Statement - Switch Case.pptxConditional Statement - Switch Case.pptx
Conditional Statement - Switch Case.pptx
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

More from Ducat India

More from Ducat India (20)

Join MCSA Server 2016 And 2019 Course In Noida
Join MCSA Server 2016 And 2019 Course In NoidaJoin MCSA Server 2016 And 2019 Course In Noida
Join MCSA Server 2016 And 2019 Course In Noida
 
Apply now for dot net training classes in Noida
Apply now for dot net training classes in NoidaApply now for dot net training classes in Noida
Apply now for dot net training classes in Noida
 
Apply now for linux training classes in noida
Apply now for linux training classes in noidaApply now for linux training classes in noida
Apply now for linux training classes in noida
 
Apply Now for DevOps Training Classes in Noida
Apply Now for DevOps Training Classes in NoidaApply Now for DevOps Training Classes in Noida
Apply Now for DevOps Training Classes in Noida
 
Apply Now for AutoCAD Training Course in Noida
Apply Now for AutoCAD Training Course in NoidaApply Now for AutoCAD Training Course in Noida
Apply Now for AutoCAD Training Course in Noida
 
Amazon Elastic Load Balancing
Amazon Elastic Load BalancingAmazon Elastic Load Balancing
Amazon Elastic Load Balancing
 
AWS Relation Database Services
AWS Relation Database ServicesAWS Relation Database Services
AWS Relation Database Services
 
Microsoft Dynamics CRM – Web Resources
Microsoft Dynamics CRM – Web ResourcesMicrosoft Dynamics CRM – Web Resources
Microsoft Dynamics CRM – Web Resources
 
Field Types
Field TypesField Types
Field Types
 
Sprint in jira
Sprint in jiraSprint in jira
Sprint in jira
 
JIRA Versions
JIRA VersionsJIRA Versions
JIRA Versions
 
Kanban Board in Jira
Kanban Board in JiraKanban Board in Jira
Kanban Board in Jira
 
Test Report Preparation
Test Report PreparationTest Report Preparation
Test Report Preparation
 
What is Text Analysis?
What is Text Analysis?What is Text Analysis?
What is Text Analysis?
 
Data Science Using Scikit-Learn
Data Science Using Scikit-LearnData Science Using Scikit-Learn
Data Science Using Scikit-Learn
 
Struts 2 – Database Access
Struts 2 – Database AccessStruts 2 – Database Access
Struts 2 – Database Access
 
Struts 2 – Interceptors
Struts 2 – InterceptorsStruts 2 – Interceptors
Struts 2 – Interceptors
 
Struts 2 – Architecture
Struts 2 – ArchitectureStruts 2 – Architecture
Struts 2 – Architecture
 
Hibernate 5 – merge() Example
Hibernate 5 – merge() ExampleHibernate 5 – merge() Example
Hibernate 5 – merge() Example
 
Hibernate Object States – Transient,Persistent and Detached
Hibernate Object States – Transient,Persistent and DetachedHibernate Object States – Transient,Persistent and Detached
Hibernate Object States – Transient,Persistent and Detached
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Switch Case Statement

  • 1. Language | Industrial Training | Digital Marketing | Web Technology | Testing+ | Database | Networking | Mobile Application | ERP | Graphic | Big Data | Cloud Computing Call us: 70-70-90-50-90 www.ducatindia.com Apply Now
  • 2. Switch Case Statement When a value requires different actions for a fixed set of values, the if might get more complex, the more the set of values increases. In this case the more suitable statement is the switch statement. Syntax switch ([onvar]) { case [option]: [statement;] break; … default: [statement;] }
  • 3. The terms in square brackets are detailed in the following list. • [onvar] is the variable that is tested against the case statements to select a statement. It can be of any primitive type, enumerations and starting with Java 7, String. Clearly the switch statement is not limited by conditions evaluated to boolean results, which allows for a lot of flexibility. • case [option] is a value the variable is matched upon to make a decision regarding the statement to execute. A case as the keyword states. • [statement] is a statement or a groups of statements to execute when [onvar] == [option]. Considering that there is no else branch, we have to make sure that only the statement(s) corresponding to the first match is executed, which is where the break; statement comes in. The break statement stops the current execution path and moves the execution point to the next statement outside the statement that contains it. I’ll cover it later in the chapter. Without it, after the first match, all subsequent cases are traversed, and statements corresponding to them are executed. • So, if we execute the preceding program and we provide number 7 as an argument, the text Summer is printed. But if the break statements for case 7 and 8 are commented, the output changes to Autumn. • default [statement;] is a statement that is executed when no match on a case has been found, the default case does not need a break statement. If the previous program is run with any number outside the [1-12] interval, Error is printed because the default statement is executed. • Now that you understand how switch works, let’s look at how we can reduce the previous statement. The month example is suitable here, because it can further be modified to show how the switch statement can be simplified, when a single statement should be executed for multiple cases. In our code, writing each assignment statement three times is a little redundant. switch can be written in a different way to avoid that by grouping the cases.
  • 4. Example public class SwitchExample { public static void main(String[] args) { //Declaring a variable for switch expression int number=200; //Switch expression switch(number){ //Case statements case 100: System.out.println(“100”); break; case 200: System.out.println(“200”); break;
  • 5. case 300: System.out.println(“300”); break; //Default case statement default:System.out.println(“Not in 100, 200 or 300”); } } } Output 200
  • 7. Example public class SwitchDayExample { public static void main(String[] args) { int day=7; String dayString=””; switch(day){ case 1: dayString=”1 – Monday”; break; case 2: dayString=”2 – Teusday”; break; case 3: dayString=”3 – Wednesday”; break; case 4: dayString=”4 – Thursday”;
  • 8. break; case 5: dayString=”5 – Friday”; break; case 6: dayString=”6 – Saturday”; break; case 7: dayString=”7 – Sunday”; break; default:System.out.println(“Sunday close”); } System.out.println(dayString); } } Output 7 – Sunday