Jav Switch

🛑 ALL INFORMATION CLICK HERE 👈🏻👈🏻👈🏻
Jav Switch
Learn to code — free 3,000-hour curriculum
You use the switch statement in Java to execute a particular code block when a certain condition is met.
Above, the expression in the switch parenthesis is compared to each case . When the expression is the same as the case , the corresponding code block in the case gets executed.
If all the cases do not match the expression , then the code block defined under the default keyword gets executed.
We use the break keyword to terminate the code whenever a certain condition is met (when the expression matches with a case ).
In the code above, June is printed out. Don't worry about the bulky code. Here's a breakdown to help you understand:
We created an integer called month and assigned a value of 6 to it: int month = 6; .
Next, we created a switch statement and passed in the month variable as a parameter: switch (month){...} .
The value of month , which is acting as the expression for the switch statement, will be compared with every case value in the code. We have case 1 to 12.
The value of month is 6 so it matches with case 6. This is why the code in case 6 was executed. Every other code block got ignored.
Here's another example to simplify things:
In the example above, we created a string called username which has a value of "John".
In the switch statement, username is passed in as the expression. We then created three cases – "Doe", "John", and "Jane".
Out of the three classes, only one matches the value of username — "John". As a result, the code block in case "John" got executed.
In the examples in the previous section, our code got executed because one case matched an expression .
In this section, you'll see how to use the default keyword. You can use it as a fallback in situations where none of the cases match the expression .
The username variable in the example above has a value of "Ihechikara".
The code block for the default keyword will be executed because none of the cases created match the value of username .
In this article, we saw how to use the switch statement in Java.
We also talked about the switch statement's expression, cases, and default keyword in Java along with their use cases with code examples.
This author's bio can be found in his articles!
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
You can make a tax-deductible donation here .
Courses
Tutorials
Examples
Course Index
Explore Programiz
Python
JavaScript
SQL
C
C++
Java
Kotlin
Swift
C#
DSA
Learn Java practically
and Get Certified .
ENROLL FOR FREE!
Join our newsletter for the latest updates.
Join our newsletter for the latest updates.
Examples
Python Examples
JavaScript Examples
C
Examples
Java Examples
Kotlin Examples
C++ Examples
Company
Change Ad Consent
Do not sell my data
About
Advertising
Privacy Policy
Terms & Conditions
Contact
Blog
Youtube
Apps
Learn Python
Learn C Programming
Learn Java
Make your summer productive. Try hands-on Java with Programiz PRO.
Claim Discount
Learn Java practically
and Get Certified .
Learn Java practically
and Get Certified .
In this tutorial, you will learn to use the switch statement in Java to control the flow of your program’s execution with the help of examples.
The switch statement allows us to execute a block of code among many alternatives.
The syntax of the switch statement in Java is:
How does the switch-case statement work?
The expression is evaluated once and compared with the values of each case.
Note : The working of the switch-case statement is similar to the Java if...else...if ladder . However, the syntax of the switch statement is cleaner and much easier to read and write.
In the above example, we have used the switch statement to find the size. Here, we have a variable number . The variable is compared with the value of each case statement.
Since the value matches with 44 , the code of case 44 is executed.
Here, the size variable is assigned with the value Large .
Notice that we have been using break in each case block.
The break statement is used to terminate the switch-case statement. If break is not used, all the cases after the matching case are also executed. For example,
In the above example, expression matches with case 2 . Here, we haven't used the break statement after each case.
Hence, all the cases after case 2 are also executed.
This is why the break statement is needed to terminate the switch-case statement after the matching case. To learn more, visit Java break Statement .
The switch statement also includes an optional default case . It is executed when the expression doesn't match any of the cases. For example,
In the above example, we have created a switch-case statement. Here, the value of expression doesn't match with any of the cases.
Hence, the code inside the default case is executed.
Note : The Java switch statement only works with:
© Parewa Labs Pvt. Ltd. All rights reserved.
Try Programiz PRO:
Learn to code interactively with step-by-step guidance.
Come write articles for us and get featured
Learn and code with the best industry experts
Get access to ad-free content, doubt assistance and more!
Come and find your dream job with us
Difficulty Level :
Easy Last Updated :
25 Jun, 2022
// Java program to Demonstrate Switch Case
public static void main(String[] args)
// Switch statement with int data type
dayString = "Monday" ;
dayString = "Tuesday" ;
dayString = "Wednesday" ;
dayString = "Thursday" ;
dayString = "Friday" ;
dayString = "Saturday" ;
dayString = "Sunday" ;
dayString = "Invalid day" ;
System.out.println(dayString);
// Java Program to Demonstrate Switch Case
// with Multiple Cases Without Break Statements
public static void main(String[] args)
dayString = "Monday" ;
dayString = "Tuesday" ;
dayString = "Wednesday" ;
dayString = "Thursday" ;
dayString = "Friday" ;
dayString = "Saturday" ;
dayString = "Sunday" ;
dayString = "Invalid day" ;
// Multiple cases without break statements
dayType = "Invalid daytype" ;
System.out.println(dayString + " is a " + dayType);
public static void main(String[] args)
"elective courses : Advance english, Algebra" );
// Break statement to hault execution here
// itself if case is matched
// Switch inside a switch
System.out.println(
"elective courses : Machine Learning, Big Data" );
System.out.println(
"elective courses : Antenna Engineering" );
// It will execute if above cases does not
// Print statement
System.out.println(
"Elective courses : Optimization" );
// Java Program to Illustrate Use of Enum
public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
public static void main(String args[])
Day[] DayNow = Day.values();
// Iterating using for each loop
System.out.println( "Sunday" );
// break statement that hault further
// execution once case is satisfied
System.out.println( "Monday" );
System.out.println( "Tuesday" );
System.out.println( "Wednesday" );
System.out.println( "Thursday" );
System.out.println( "Friday" );
System.out.println( "Saturday" );
Enhancements for Switch Statement in Java 13
Library Management System Using Switch Statement in Java
8 Reasons Why You Should Switch To Kotlin From Java
Why You Should Switch to Kotlin from Java to Develop Android Apps?
Usage of Enum and Switch Keyword in Java
Three way partitioning using Dutch National Sort Algorithm(switch-case version) in Java
Decision Making in Java (if, if-else, switch, break, continue, jump)
Unreachable statement using final and non-final variable in Java
Java if-else statement with Examples
Break and Continue statement in Java
Java Program to Print any Statement without Using the Main Method
How to Use Callable Statement in Java to Call Stored Procedure?
Menu-Driven program using Switch-case in C
How to Switch Themes in Android Using RadioButtons?
How to Add Switch in Android ActionBar?
How to Save Switch Button State in Android?
JAVA Programming Foundation- Self Paced Course
Data Structures & Algorithms- Self Paced Course
Complete Interview Preparation- Self Paced Course
Improve your Coding Skills with Practice Try It!
A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh - 201305
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Got It !
The switch statement is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions. It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. It basically tests the equality of variables against multiple values.
Note: Java switch expression must be of byte, short, int, long(with its Wrapper type), enums and string. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class, and Wrapper classes.
Note: Java switch statement is a fall through statement that means it executes all statements if break keyword is not used, so it is highly essential to use break keyword inside each case.
Example: Consider the following java program, it declares an int named day whose value represents a day(1-7). The code displays the name of the day, based on the value of the day, using the switch statement.
A break statement is optional. If we omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. For instance, let us consider the updated version of the above program, it also displays whether a day is a weekday or a weekend day.
We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch.
This article is contributed by Gaurav Miglani . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Writing code in comment?
Please use ide.geeksforgeeks.org ,
generate link and share the link here.
Trail: Learning the Java Language
Lesson: Language Basics
Section: Control Flow Statements
Home Page
>
Learning the Java Language
>
Language Basics
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
... // and so on
public class SwitchDemoFallThrough {
public static void main(String[] args) {
java.util.ArrayList futureMonths =
new java.util.ArrayList();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
August
September
October
November
December
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
« Previous
•
Trail
•
Next »
Previous page: The if-then and if-then-else Statements
Next page: The while and do-while Statements
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in
Enum Types ), the
String class, and a few special classes that wrap certain primitive types:
Character ,
Byte ,
Short , and
Integer (discussed in
Numbe
17 Girls Porno
Hot Amateur Sex Porn
Retro Mature Swinger