Chuyển tới nội dung
Home » Java 11 Switch Case | What’S A Rich Text Element?

Java 11 Switch Case | What’S A Rich Text Element?

#15 Switch Statement in Java

Conclusion

The Java releases up to and including 13 are rather manageable in terms of their innovations. This is true even for Java 11 as an LTS version. Fortunately, Java 14 brings a good slew of useful enhancements: On the one hand, there are the convenient syntax changes in switch. Another is the multi-line strings, called Text Blocks. These are covered in one of the next blogs.

Let me conclude: The new syntax of switch seems to be just a small change, but it has an enormous effect on readability and ease of use. This blog introduced the benefits and simplifications of the new syntax of switch so that you can profit from it in your own projects.

6 Switch Expressions

Like all expressions,

switch

expressions evaluate to a
single value and can be used in statements. They may contain ”

case L ->


labels that eliminate the need for

break

statements to prevent fall
through. You can use a

yield

statement to specify the value of a switch
expression.

For background information about the design of

switch

expressions, see
JEP 361.

“case L ->” Labels

Consider the following

switch

statement that prints the
number of letters of a day of the week:


public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } // ... int numLetters = 0; Day day = Day.WEDNESDAY; switch (day) { case MONDAY: case FRIDAY: case SUNDAY: numLetters = 6; break; case TUESDAY: numLetters = 7; break; case THURSDAY: case SATURDAY: numLetters = 8; break; case WEDNESDAY: numLetters = 9; break; default: throw new IllegalStateException("Invalid day: " + day); } System.out.println(numLetters);

It would be better if you could “return” the length of the day’s name
instead of storing it in the variable

numLetters

; you can do this
with a

switch

expression. Furthermore, it would be better if you
didn’t need

break

statements to prevent fall through; they are
laborious to write and easy to forget. You can do this with a new kind of

case

label. The following is a

switch

expression that uses the new kind of

case

label to print the number
of letters of a day of the week:


Day day = Day.WEDNESDAY; System.out.println( switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; default -> throw new IllegalStateException("Invalid day: " + day); } );

The new kind of

case

label has the following form:


case label_1, label_2, ..., label_n -> expression;|throw-statement;|block

When the Java runtime matches any of the labels to the left of the arrow,
it runs the code to the right of the arrow and does not fall through; it does not
run any other code in the

switch

expression (or statement). If the
code to the right of the arrow is an expression, then the value of that expression
is the value of the

switch

expression.

You can use the new kind of

case

label in

switch

statements. The following is like the first example,
except it uses ”

case L ->

” labels instead of ”

case
L:

” labels:


int numLetters = 0; Day day = Day.WEDNESDAY; switch (day) { case MONDAY, FRIDAY, SUNDAY -> numLetters = 6; case TUESDAY -> numLetters = 7; case THURSDAY, SATURDAY -> numLetters = 8; case WEDNESDAY -> numLetters = 9; default -> throw new IllegalStateException("Invalid day: " + day); }; System.out.println(numLetters);

A ”

case L ->

” label along with its code to its right is called a
switch labeled rule.

“case L:” Statements and the yield Statement

You can use ”

case L:

” labels in

switch

expressions; a ”

case L:

” label along with its code to the right is
called a switch labeled statement group:


Day day = Day.WEDNESDAY; int numLetters = switch (day) { case MONDAY: case FRIDAY: case SUNDAY: System.out.println(6); yield 6; case TUESDAY: System.out.println(7); yield 7; case THURSDAY: case SATURDAY: System.out.println(8); yield 8; case WEDNESDAY: System.out.println(9); yield 9; default: throw new IllegalStateException("Invalid day: " + day); }; System.out.println(numLetters);

The previous example uses

yield

statements. They take
one argument, which is the value that the

case

label produces in a

switch

expression.

The

yield

statement makes it easier for you to
differentiate between

switch

statements and

switch

expressions. A

switch

statement, but not a

switch

expression, can be the target of a

break

statement. Conversely, a

switch

expression, but not a

switch

statement,
can be the target of a

yield

statement.

Note:

It’s recommended that you use ”

case L ->

” labels.
It’s easy to forget to insert

break

or

yield

statements when using ”

case L:

” labels; if you do, you might
introduce unintentional fall through in your code.

For ”

case L ->

” labels, to specify multiple
statements or code that are not expressions or

throw

statements, enclose them in a block. Specify the value that the

case

label produces with the

yield

statement:


int numLetters = switch (day) { case MONDAY, FRIDAY, SUNDAY -> { System.out.println(6); yield 6; } case TUESDAY -> { System.out.println(7); yield 7; } case THURSDAY, SATURDAY -> { System.out.println(8); yield 8; } case WEDNESDAY -> { System.out.println(9); yield 9; } default -> { throw new IllegalStateException("Invalid day: " + day); } };

Exhaustiveness

Unlike

switch

statements, the cases of

switch

expressions must be exhaustive, which means that for all possible values,
there must be a matching switch label. Thus,

switch

expressions
normally require a

default

clause. However, for

enum


switch

expressions that cover all known constants, the compiler
inserts an implicit

default

clause.

In addition, a

switch

expression must either complete normally with
a value or complete abruptly by throwing an exception. For example, the following
code doesn’t compile because the switch labeled rule doesn’t contain a

yield

statement:


int i = switch (day) { case MONDAY -> { System.out.println("Monday"); // ERROR! Block doesn't contain a yield statement } default -> 1; };

The following example doesn’t compile because the switch labeled statement group doesn’t contain a yield statement:


i = switch (day) { case MONDAY, TUESDAY, WEDNESDAY: yield 0; default: System.out.println("Second half of the week"); // ERROR! Group doesn't contain a yield statement };


switchexpression must evaluate to a single value (or throw an exception), you can't jump through a


switchexpression with a


break,


yield,


return, or


continuestatement, like in the following example:


z: for (int i = 0; i < MAX_VALUE; ++i) { int k = switch (e) { case 0: yield 1; case 1: yield 2; default: continue z; // ERROR! Illegal jump through a switch expression }; // ... }

#15 Switch Statement in Java
#15 Switch Statement in Java

What’s a Rich Text element?

The rich text element allows you to create and format headings, paragraphs, blockquotes, images, and video all in one place instead of having to add and format them individually. Just double-click and easily create content.

Static and dynamic content editing

A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

How to customize formatting for each rich text

Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the “When inside of” nested selector system.

You use the

switch

statement in Java to execute a particular code block when a certain condition is met.

Here’s what the syntax looks like:


switch(expression) { case 1: // code block break; case 2: // code block break; case 3: // code block break; default: // code block }

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

).

Let’s see some code examples.

Multiple matching values

What if a fallthrough was desired? In the old ways, we would have to write a separate case for each value and let it fall through to the last case which will contain the operations.


// OLD (fallthrough) switch (x) { case 1: case 2: System.out.println("Valid values"); break; default: System.out.println("Unknown"); }

In the improved version, this can be done with a comma separated list of values.


// NEW (multiple values) switch (x) { case 1, 2: System.out.println("Valid values"); default: System.out.println("Unknown"); }

switch Statement in Java
switch Statement in Java

The switch expression:

The

switch

expression was introduced with Java SE 12. However, it remained as a Preview feature in Java SE 12 and 13 and finally got standardized with Java SE 14. Like any expression,

switch

expressions evaluate to a single value, and can be used in statements. It also introduced “arrow

case

” labels eliminating the need for

break

statements to prevent fall through. As of Java SE 15, there is no change in the supported data types (mentioned in the

switch

statement section above).

Demo


enum PaymentStatus { UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN; } public class Main { public static void main(String[] args) { PaymentStatus paymentStatus = PaymentStatus.PARTPAID; String message = switch (paymentStatus) { case UNPAID -> "The order has not been paid yet. Please make the minimum/full amount to procced."; case PARTPAID -> "The order is partially paid. Some features will not be available. Please check the brochure for details."; case PAID -> "The order is fully paid. Please choose the desired items from the menu."; default -> throw new IllegalStateException("Invalid payment status: " + paymentStatus); }; System.out.println(message); } }

Output:


The order is partially paid. Some features will not be available. Please check the brochure for details.

Arrow Case Expression

Earlier, case blocks were required to end with a break statement. Otherwise, there would be a fall-through problem.


// OLD switch (x) { case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; default: System.out.println("Unknown"); }

Now, we can use an arrow case expression to simplify the case block. Only the statement appearing after the arrow will be executed if the case matches.


// NEW switch (x) { case 1 -> System.out.println("One"); case 2 -> System.out.println("Two"); default -> throw new IllegalArgumentException(); }

This is similar to lambda syntax. If there were multiple statements, we could use a block instead.


// NEW (with block) switch (x) { case 1 -> { System.out.println("One"); System.out.println("One again"); } case 2 -> System.out.println("Two"); default -> System.out.println("Unknown"); }

Java switch ⬇【4 minutes】
Java switch ⬇【4 minutes】

Summary

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.

Happy coding!

As part of Java SE 12,

switch

expressions were introduced and since Java SE 14, they have been standardized. How are they different from

switch

statements?

As part of Java SE 12,

  • 4What does standardized mean vs. introduced? Jan 26, 2021 at 17:00
  • 6@rogerdpack This must refer to switch expressions being introduced as Preview feature in JDK 12 – fully usable and complete, enabled through the compiler options, still amenable to (breaking) change in future versions based on user feedback. In JDK 14 this was consolidated as a standard feature that won’t change anymore in future versions.– trymanJan 27, 2021 at 9:48

The switch expression with yield:

Since Java SE 13, you can use

yield

statement, instead of the arrow operator (->), to return a value from a

switch

expression.

Demo


enum PaymentStatus { UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN; } public class Main { public static void main(String[] args) { PaymentStatus paymentStatus = PaymentStatus.PARTPAID; String message = switch (paymentStatus) { case UNPAID: yield "The order has not been paid yet. Please make the minimum/full amount to procced."; case PARTPAID: yield "The order is partially paid. Some features will not be available. Please check the brochure for details."; case PAID: yield "The order is fully paid. Please choose the desired items from the menu."; default: throw new IllegalStateException("Invalid payment status: " + paymentStatus); }; System.out.println(message); } }

Output:


The order is partially paid. Some features will not be available. Please check the brochure for details.

1 The support for

String

was added with JDK 7

  • “Unlike the if/else if/else statement, a switch statement can have a number of possible execution paths” sounds like

    switch

    could execute multiple cases for one switch. If you mean that

    switch

    supports fallthrough it would be much more clear to mention that explicitly. Other than that if/else if/else is just different syntax compared to switch statement because you can easily convert any switch statement without fallthrough to if/else if/else format. Jun 22, 2021 at 9:38

Nice writeup! But I might also add the ability to have multiple cases for a single case statement. The following example is very contrived (there are many better ways to achieve it). It does a simple frequency count of the vowels, digits, consonants, and other characters in a string.


int count[] = new int[4]; String s = "829s2bi9jskj*&@)(so2i2ksso"; for (char c : s.toCharArray()) { int i = switch (c) { case 'a', 'e', 'i', 'o', 'u' -> 0; case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> 1; case 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' -> 2; default -> 3; }; count[i]++; } System.out.printf("vowels - %d%n", count[0]); System.out.printf("digits - %d%n", count[1]); System.out.printf("consonants - %d%n", count[2]); System.out.printf("other - %d%n", count[3]);

Prints


vowels - 4 digits - 7 consonants - 10 other - 5

Adding to existing answers:

yield

can also be used with

->

and its main purpose is to allow the use of a block when a single expression is not sufficient for a given case:


var test = switch (value) { case A -> 1; case B -> 2; case C -> { System.err.println("neither A nor B"); // or some calculation yield -1; } }

I would also mention JEP-354 where the switch expression is proposed and described.Formal specification can be found, as always in the Java Language Specification.

Adding to the above answers one can look at the current “shortfalls” with switch statement which switch expression solve:

Switch Statement:

  • Issue 1: Accidental Fall-through
  • Issue 2: Variable scoping
  • Issue 3: No return value

Switch expression:

  • No fallthrough
  • Combined constants
  • Blocked scope
  • Return yield
13.  Switch case java - seri java cơ bản cho người mới - bài tập java 11
13. Switch case java – seri java cơ bản cho người mới – bài tập java 11

How to Use a Switch Case in Java

Take a look at the following code:


class CurrentMonth { public static void main(String[] args) { int month = 6; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; // June } } }

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:


class Username { public static void main(String[] args) { String username = "John"; switch (username) { case "Doe": System.out.println("Username is Doe"); break; case "John": System.out.println("Username is John"); break; case "Jane": System.out.println("Username is Jane"); break; // Username is John } } }

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.

Exhaustiveness of switch expressions

Switch case statements are not required to be exhaustive. It is fine if no case matches and there is no default case.However, when using switch to return a value, it is required that all cases are covered and one of them should always match.

For e.g., when implementing a switch on numbers, the default case cannot be left out:


// missing default case String word = switch (x) { case 1 -> "One"; case 2 -> "Two"; }; /* gives the error: error: the switch expression does not cover all possible input values String word = switch (x) { ^ */

This means, we will always need to have a default case unless working with booleans.

The only exception to this is while using an enum and covering all possible enum values.

The below code works fine but it will give the same error as above if we remove one of the cases.


// switch expressions with enum public class MyClass { static enum Color { RED, GREEN, BLUE }; public static void main(String[] args) { Color color = Color.RED; System.out.println(switch (color) { case RED -> "Red"; case GREEN -> "Green"; case BLUE -> "Blue"; }); } }

That’s it for the improvements. One more feature worth mentioning is pattern matching but I have not covered it because it is still a preview feature.

An important point to note is that having an improved syntax does not mean the old syntax is invalid now. Both syntaxes work.

Thank you for reading. If you want to connect with me, you can find me on Twitter where I post regular Java tips and quizzes.

In this blog, I will cover some improvements of switch. The old syntax dates back to the early day of Java, and its handling is a bit cumbersome.

Let’s look at the newer, slightly modified syntax for switch, called Switch Expressions. With it, case distinctions can be formulated much more elegantly than before.

13.1 Giải bài tập java 11 - ứng dụng Switch Case java - seri java 2023 chi tiết cho người mới
13.1 Giải bài tập java 11 – ứng dụng Switch Case java – seri java 2023 chi tiết cho người mới

Switch expressions

A big improvement is that switch statements can be used to return a value and therefore can be used as expressiond.

For example, we can use a switch-case block inline to print a value in words.


// switch expressions System.out.println(switch (x) { case 1 -> "One"; case 2 -> "Two"; default -> "Unknown"; });

switch Argument and case Values

Now let’s discuss the allowed types of switch argument and case values, the requirements for them and how the switch statement works with Strings.

4.Data Types

We can’t compare all the types of objects and primitives in the switch statement. A switch works only with four primitives and their wrappers as well as with the enum type and the String class:

  • byte and Byte
  • short and Short
  • int and Integer
  • char and Character
  • enum
  • String

String type is available in the switch statement starting with Java 7.

enum type was introduced in Java 5 and has been available in the switch statement since then.

Wrapper classes have also been available since Java 5.

Of course, switch argument and case values should be of the same type.

4.No null Values

We can’t pass the null value as an argument to a switch statement.

If we do, the program will throw NullPointerException, using our first switch example:


@Test(expected=NullPointerException.class)
public void whenSwitchAgumentIsNull_thenNullPointerException() {
String animal = null;
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
}

Of course, we can’t also pass null as a value to the case label of a switch statement. If we do, the code will not compile.

4.Case Values as Compile-Time Constants

If we try to replace the DOG case value with the variable dog, the code won’t compile until we mark the dog variable as final:


final String dog="DOG";
String cat="CAT";
switch (animal) {
case dog: //compiles
result = "domestic animal";
case cat: //does not compile
result = "feline"
}

4.String Comparison

If a switch statement used the equality operator to compare strings, we couldn’t compare a String argument created with the new operator to a String case value correctly.

Luckily, the switch operator uses the equals() method under the hood.

Let’s demonstrate this:


@Test
public void whenCompareStrings_thenByEqual() {
String animal = new String("DOG");
assertEquals("domestic animal", s.exampleOfSwitch(animal));
}

Java 19 . Câu lệnh switch ... case trong lập trình Java  | Phần 1 - Lập Trình Java Cơ Bản
Java 19 . Câu lệnh switch … case trong lập trình Java | Phần 1 – Lập Trình Java Cơ Bản

Modern Switch Expressions

Let’s have a critical look at the source code. First of all, the shown construct does not appear elegant and is also quite long. The multiple specifications of values need accustoming, too. Even worse, a break is needed so that the processing runs without surprise and there is no fall-through. Moreover, we need to set the (artificial) auxiliary variable numOfLetters correctly in each branch. In particular, despite the actually complete coverage of the enum values, the default is necessary. Otherwise, the compiler complains that the variable numOfLetters may not be initialized – unless you have already assigned a value to it initially. So how is it better?

Syntax of the new Switch Expressions

With the new “Switch Expressions”, expressing case distinctions is made much easier and provides an intuitive notation:

From this example, we notice some syntactic innovations: In addition to the obvious arrow instead of the colon, multiple values can now be specified after the case. Conveniently, there is no more need for break: The statements after the arrow are only executed specifically for the case and no fall-through exists with this syntax. Besides, the switch can now return a value, which avoids the need to define auxiliary variables. Instead of just stating a value after the arrow, it is also possible to specify expressions such as assignments or method calls without any problems. And even better, of course, still without the need for a break. Furthermore, this is no longer allowed in the new syntax after the arrow.

Special feature: completeness check

In the old version of switch it was possible to omit the default or to specify a case for individual values, for example WEDNESDAY. The compiler wouldn’t have recognized this in switch itself. This would only have been pointed out later when accessing the variable used in the example that it is not initialized in every case.

The handling has conveniently improved with the new switch expressions: Let’s assume we did not specify WEDNESDAY in the above example. Then this is directly criticized by the compiler: “A switch expression should cover all possible values.” Additionally, IDEs offer the choice of adding either the appropriate case or a default, but not both: full coverage of the enum values is automatically detected. This innovation is necessary because the switch must now return a value in each case.

While it is still quite clear for enums with a limited set of possible values, the following question arises: How does it work for other types, such as ints? In such cases, the compiler can only state that possibly not all values are covered, and complains: “A switch expression should cover all possible values.” Then the IDEs suggest to add a default – here indicated by the line commented out:

Conclusion

In this article, we discussed the subtleties of using the switch statement in Java. We can decide whether to use switch based on readability and the type of the compared values.

The switch statement is a good candidate for cases when we have a limited number of options in a predefined set (e.g., days of the week).

Otherwise, we’d have to modify the code each time a new value is added or removed, which may not be feasible. For these cases, we should consider other approaches such as polymorphism or other design patterns such as Command.

As always, the complete JDK 8 code and JDK 13 code is available on GitHub.

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
Numbers and Strings).

The following code example,

SwitchDemo

, declares an

int

named

month

whose value represents a month. The code displays the name of the month, based on the value of

month

, using the

switch

statement.

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); } }

In this case,

August

is printed to standard output.

The body of a

switch

statement is known as a switch block. A statement in the

switch

block can be labeled with one or more

case

or

default

labels. The

switch

statement evaluates its expression, then executes all statements that follow the matching

case

label.

You could also display the name of the month with

if-then-else

statements:

int month = 8; if (month == 1) { System.out.println(“January”); } else if (month == 2) { System.out.println(“February”); } … // and so on

Deciding whether to use

if-then-else

statements or a

switch

statement is based on readability and the expression that the statement is testing. An

if-then-else

statement can test expressions based on ranges of values or conditions, whereas a

switch

statement tests expressions based only on a single integer, enumerated value, or

String

object.

Another point of interest is the

break

statement. Each

break

statement terminates the enclosing

switch

statement. Control flow continues with the first statement following the

switch

block. The

break

statements are necessary because without them, statements in

switch

blocks fall through: All statements after the matching

case

label are executed in sequence, regardless of the expression of subsequent

case

labels, until a

break

statement is encountered. The program

SwitchDemoFallThrough

shows statements in a

switch

block that fall through. The program displays the month corresponding to the integer

month

and the months that follow in the year:

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); } } } }

This is the output from the code:

August September October November December

Technically, the final

break

is not required because flow falls out of the

switch

statement. Using a

break

is recommended so that modifying the code is easier and less error prone. The

default

section handles all values that are not explicitly handled by one of the

case

sections.

The following code example,

SwitchDemo2

, shows how a statement can have multiple

case

labels. The code example calculates the number of days in a particular month:

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); } }

This is the output from the code:

Number of Days = 29

In Java SE 7 and later, you can use a

String

object in the

switch

statement’s expression. The following code example,

StringSwitchDemo

, displays the number of the month based on the value of the

String

named

month

:

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); } } }

The output from this code is .

The

String

in the

switch

expression is compared with the expressions associated with each

case

label as if the

String.equals

method were being used. In order for the

StringSwitchDemo

example to accept any month regardless of case,

month

is converted to lowercase (with the

toLowerCase

method), and all the strings associated with the

case

labels are in lowercase.

Note: This example checks if the expression in the

switch

statement is

null

. Ensure that the expression in any

switch

statement is not null to prevent a

NullPointerException

from being thrown.

Bài viết được sự cho phép của tác giả Nguyễn Hữu Khanh

Khi làm việc với switch statement, các bạn sẽ hay gặp những vấn đề sau:

  • Vấn đề thứ nhất là chúng ta quên khai báo break statement: điều này có nghĩa code chúng ta sẽ không thoát khỏi switch statement sau khi match case đầu tiên mà sẽ thực thi tiếp những case tiếp theo, ví dụ như:

package com.huongdanjava; public class SwitchExample { public static void main(String[] args) { int a = 1; int b = 2; switch (a + b) { case 2: System.out.println(“Khanh”); break; case 3: System.out.println(“Huong Dan Java”); case 4: System.out.println(“Lap Trinh Java”); default: System.out.println(“Hello”); break; } } }

Kết quả:

  • Vấn đề thứ hai là nếu các bạn muốn trong trường hợp giá trị của biến với các giá trị khác nhau a và b thì xử lý cùng một đoạn code. Chúng ta sẽ viết code như sau:

package com.huongdanjava; public class SwitchExample { public static void main(String[] args) { int a = 1; int b = 2; switch (a + b) { case 2: System.out.println(“Khanh”); break; case 3: System.out.println(“Huong Dan Java”); break; case 4: System.out.println(“Huong Dan Java”); break; default: System.out.println(“Hello”); break; } } }

Hoặc:

package com.huongdanjava; public class SwitchExample { public static void main(String[] args) { int a = 1; int b = 2; switch (a + b) { case 2: System.out.println(“Khanh”); break; case 3: case 4: System.out.println(“Huong Dan Java”); break; default: System.out.println(“Hello”); break; } } }

Những cách viết này bất tiện vì duplicate code hoặc chúng ta đôi khi không control được nên đặt break statement ở chỗ nào.

  • Vấn đề thứ ba là nếu các bạn muốn sử dụng switch statement để determine giá trị của một biến nào đó, các bạn phải viết như sau:

package com.huongdanjava; public class SwitchExample { public static void main(String[] args) { String message = “”; int n = 1; switch (n) { case 1: message = “Khanh”; break; case 2: message = “Huong Dan Java”; break; case 3: message = “Lap Trinh Java”; break; default: break; } System.err.println(message); } }

Để giải quyết những vấn đề trên, từ Java 12, các bạn có thể viết switch statement với những cải tiến như sau:

  • Đối với vấn đề thứ nhất, Java 12 hỗ trợ chúng ta cách viết switch statement giống như lambda expression, ví dụ như:

package com.huongdanjava; public class SwitchExample { public static void main(String[] args) { int a = 1; int b = 2; switch (a + b) { case 2 -> System.out.println(“Khanh”); case 3 -> System.out.println(“Huong Dan Java”); case 4 -> System.out.println(“Lap Trinh Java”); default -> System.out.println(“Hello”); } } }

Kết quả:

Đối với vấn đề thứ 2 thì các bạn có thể viết lại switch statement như sau:

package com.huongdanjava; public class SwitchExample { public static void main(String[] args) { int a = 1; int b = 2; switch (a + b) { case 2 -> System.out.println(“Khanh”); case 3, 4 -> System.out.println(“Huong Dan Java”); default -> System.out.println(“Hello”); } } }

Kết quả:

Còn đối vấn đề thứ ba thì bây giờ Java 12 đã hỗ trợ chúng ta return lại value với switch statement như sau:

package com.huongdanjava; public class SwitchExample { public static void main(String[] args) { int n = 1; var message = switch (n) { case 1 -> “Khanh”; case 2 -> “Huong Dan Java”; case 3 -> “Lap Trinh Java”; default -> “Hello”; }; System.out.println(message); } }

Kết quả:

Nếu các bạn muốn thêm code để xử lý business logic trong mỗi case của switch statement thì các bạn cần upgrade lên Java 13, sau đó thêm code và sử dụng từ khóa yield để return lại giá trị mà mình mong muốn. Ví dụ như sau:

package com.huongdanjava; public class SwitchExample { public static void main(String[] args) { int n = 1; var message = switch (n) { case 1 -> “Khanh”; case 2 -> “Huong Dan Java”; case 3 -> “Lap Trinh Java”; default -> “Hello”; }; System.out.println(message); } }

Kết quả:

Java 12 introduced switch expressions which improved the way we can write switch-case statements.

Over the next few versions, the switch-case statement has been improved several times. Let’s take a look at the improvements and compare them to the original switch-case statement.

Switch Case in Java #35
Switch Case in Java #35

Example of Use

Let’s say we have the following nested if-else statements:


public String exampleOfIF(String animal) {
String result;
if (animal.equals("DOG") || animal.equals("CAT")) {
result = "domestic animal";
} else if (animal.equals("TIGER")) {
result = "wild animal";
} else {
result = "unknown animal";
}
return result;
}

The above code doesn’t look good and would be hard to maintain and reason about.

To improve readability, we could make use of a switch statement:


public String exampleOfSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
result = "domestic animal";
break;
case "CAT":
result = "domestic animal";
break;
case "TIGER":
result = "wild animal";
break;
default:
result = "unknown animal";
break;
}
return result;
}

We compare the switch argument animal with the several case values. If none of the case values is equal to the argument, the block under the default label is executed.

Simply put, the break statement is used to exit a switch statement.

Overview

In this tutorial, we’ll learn what the switch statement is and how to use it.

The switch statement allows us to replace several nested if-else constructs and thus improve the readability of our code.

Switch has evolved over time. New supported types have been added, particularly in Java 5 and 7. Also, it continues to evolve — switch expressions will likely be introduced in Java 12.

Below we’ll give some code examples to demonstrate the use of the switch statement, the role of the break statement, the requirements for the switch argument/case values and the comparison of Strings in a switch statement.

Let’s move on to the example.

What's new in Java Switch | Switch Statement and Expression
What’s new in Java Switch | Switch Statement and Expression

Introductory example

To demonstrate switch expressions, I resort to mapping days of the week to their textual length as an example.

To better understand the need for this syntax improvement, let’s first examine how this task would have been formulated with the old syntax. Afterwards, we’ll look at the advantages provided by the new syntax of switch.

Analysis: What were some weaknesses of the switch so far?

Let’s start with the implementation of mapping weekdays of type DayOfWeek to their textual length using the older syntax:

The switch statement:

Unlike the

if/else if/else

statement, a

switch

statement can have a number of possible execution paths. A

switch

works with the primitive types,

byte

,

short

,

char

, and

int

, their respective wrapper types (

Byte

,

Short

,

Character

, and

Integer

), enumerated types, and the

String

type1. While an

if-else

statement is used to test expressions based on ranges of values or conditions, a

switch

statement is used to test expressions based only on a single value.

Demo


enum PaymentStatus { UNPAID, PARTPAID, PAID, DISPUTED, UNKNOWN; } public class Main { public static void main(String[] args) { String message = ""; PaymentStatus paymentStatus = PaymentStatus.PARTPAID; switch (paymentStatus) { case UNPAID: message = "The order has not been paid yet. Please make the minimum/full amount to procced."; break; case PARTPAID: message = "The order is partially paid. Some features will not be available. Please check the brochure for details."; break; case PAID: message = "The order is fully paid. Please choose the desired items from the menu."; break; default: throw new IllegalStateException("Invalid payment status: " + paymentStatus); } System.out.println(message); } }

Output:


The order is partially paid. Some features will not be available. Please check the brochure for details.

Pseb class 12 computer science term 2 syllabus revision
Pseb class 12 computer science term 2 syllabus revision

switch Expressions

JDK 13 is now available and brings an improved version of a new feature first introduced in JDK 12: the switch expression.

In order to enable it, we need to pass –enable-preview to the compiler.

5.The New switch Expression

Let’s see what the new switch expression looks like when switching over months:


var result = switch(month) {
case JANUARY, JUNE, JULY -> 3;
case FEBRUARY, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER -> 1;
case MARCH, MAY, APRIL, AUGUST -> 2;
default -> 0;
};

Sending in a value such as Month.JUNE would set result to 3.

Notice that the new syntax uses the -> operator instead of the colon we’re used to with switch statements. Also, there’s no break keyword: The switch expression doesn’t fall through cases.

Another addition is the fact that we can now have comma-delimited criteria.

5.The yield Keyword

Going a bit further, there’s a possibility to obtain fine-grain control over what’s happening on the right side of the expression by using code blocks.

In such a case, we need to use the keyword yield:


var result = switch (month) {
case JANUARY, JUNE, JULY -> 3;
case FEBRUARY, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER -> 1;
case MARCH, MAY, APRIL, AUGUST -> {
int monthLength = month.toString().length();
yield monthLength * 4;
}
default -> 0;
};

While our example is a bit arbitrary, the point is that we’ve got access to more of the Java language here.

5.Returning Inside switch Expressions

As a consequence of the distinction between switch statements and switch expressions, it is possible to return from inside a switch statement, but we’re not allowed to do so from within a switch expression.

The following example is perfectly valid and will compile:


switch (month) {
case JANUARY, JUNE, JULY -> { return 3; }
default -> { return 0; }
}

However, the following code will not compile, as we are trying to return outside of an enclosing switch expression:


var result = switch (month) {
case JANUARY, JUNE, JULY -> { return 3; }
default -> { return 0; }
};

5.Exhaustiveness

When using switch statements, it doesn’t really matter if all cases are covered.

The following code, for example, is perfectly valid and will compile:


switch (month) {
case JANUARY, JUNE, JULY -> 3;
case FEBRUARY, SEPTEMBER -> 1;
}

For switch expressions though, the compiler insists that all possible cases are covered.

The following code snippet would not compile, as there’s no default case and not all possible cases are covered:


var result = switch (month) {
case JANUARY, JUNE, JULY -> 3;
case FEBRUARY, SEPTEMBER -> 1;
}

The switch expression, however, will be valid when all possible cases are covered:


var result = switch (month) {
case JANUARY, JUNE, JULY -> 3;
case FEBRUARY, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER -> 1;
case MARCH, MAY, APRIL, AUGUST -> 2;
}

Please note that the above code snippet does not have a default case. As long as all cases are covered, the switch expression will be valid.

The break Statement

Although most of the switch statements in real life imply that only one of the case blocks should be executed, the break statement is necessary to exit a switch after the block completes.

If we forget to write a break, the blocks underneath will be executed.

To demonstrate this, let’s omit the break statements and add the output to the console for each block:


public String forgetBreakInSwitch(String animal) {
switch (animal) {
case "DOG":
System.out.println("domestic animal");
default:
System.out.println("unknown animal");
}
}

Let’s execute this code forgetBreakInSwitch(“DOG”) and check the output to prove that all the blocks get executed:


domestic animal
unknown animal

So, we should be careful and add break statements at the end of each block unless there is a need to pass through to the code under the next label.

The only block where a break is not necessary is the last one, but adding a break to the last block makes the code less error-prone.

We can also take advantage of this behavior to omit break when we want the same code executed for several case statements.

Let’s rewrite the example in the previous section by grouping together the first two cases:


public String exampleOfSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
case "CAT":
result = "domestic animal";
break;
case "TIGER":
result = "wild animal";
break;
default:
result = "unknown animal";
break;
}
return result;
}

11 - Switch Statement and Char | Java Tutorial Series
11 – Switch Statement and Char | Java Tutorial Series

EXAMPLE:

Switch Statement:


private static void oldSwitchStatement(String month) { int i = 0; String quarter = ""; switch (month) { case "JAN": case "FEB": case "MAR": i = i + 1; quarter = "Q1"; // break; case "APR": case "MAY": case "JUN": i = i + 2; quarter = "Q2"; // break; case "JUL": case "AUG": case "SEP": i = i + 3; quarter = "Q3"; // break; case "OCT": case "NOV": case "DEC": i = i + 4; quarter = "Q4"; default: System.out.println("Unknown case"); } System.out.println("QUARTER: "+ i + " "+ quarter); }

Switch Expression


private static String newSwitchExpressionYield(String month) { return switch (month) { case "JAN", "FEB", "MAR" -> "Q1"; case "APR", "MAY", "JUN" -> { System.out.println("Using yield."); yield "Q2"; } case "JUL", "AUG", "SEP" -> "Q3"; case "OCT", "NOV", "DEC" -> "Q4"; default -> "Unknown case"; }; }

To test the above pass

oldSwitchStatement("APR");

and

newSwitchExpressionYield("APR");

and see the resutls.

The yield keyword

When case has a single statement, as seen above, the value returned by the statement is returned by the switch expression.If case has a block, we need to explicitly return the value using the yield keyword.


// switch expressions with yield String word = switch (x) { case 1 -> { doSomething(); yield "One"; } case 2 -> "Two"; default -> "Unknown"; };

Old-style case blocks can also be used in switch expressions and can have a yield statement.When using a yield statement, a break statement is not required.

This is not recommended though. It’s best to stick to the new style in order to avoid confusion and unexpected mistakes.


// old-style case blocks with yield String word = switch (x) { case 1: doSomething(); yield "One"; case 2: yield "Two"; default: yield "Unknown"; };

C - Bài 11A: Cấu trúc rẽ nhánh switch-case.
C – Bài 11A: Cấu trúc rẽ nhánh switch-case.

Other reasons for the innovation

Let me go into more detail about the completeness check of the value coverage in the cases because there are sometimes difficulties when using switch.

Pitfall 1: Incomplete value specifications

With the Date and Time API, of course, the complicated construct could be simplified significantly: month.getDisplayName(TextStyle.FULL, Locale.UK).

In the following, we want to map a value from the enumeration java.time.Month to the corresponding month name. Conventionally, this can be solved somewhat as follows:

Again, the shown construct is not really elegant. Depending on whether a case is de fined for the value Month.JULY or not, one gets the value “July” or “N/A”. Also, a break is needed to ensure that the processing is performed without surprise.

Pitfall 2: Fall-through and default between the breaks

Let’s consider something rather clumsy, namely the default in the middle of the cases and without a break:

The input Month.FEBRUARY results in the value “February” as expected, but surprisingly this also happens for the input Month.JULY. Why is this? First, because of the cases unlisted value JULY, the default branch is executed. Because of the missing break, a fall-through is also (unexpectedly) triggered. This causes the code for case FEBRUARY to be executed, which can be quite confusing.

Remedy with the new switch expressions

With the help of the new syntax, the whole thing is much easier to write as follows:

It is especially worth mentioning that one can directly return the value calculated by the switch construct. Furthermore, the fall-through does not occur. Thus the input Month.FEBRUARY returns “February” as expected, and moreover the default in the middle of the cases is not quite as dramatic, though certainly not pretty either. Unlike the old syntax, the input Month.JULY just no longer results in an unexpected output “February”, but as specified by default in “N/A”. Furthermore, if there were a case JULY, it would always be executed, regardless of the position of the default, thus analogous to the behavior of the previous switch statement.

How to Use the Default Keyword in a Switch Statement

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

.

Here’s an example:


class Username { public static void main(String[] args) { String username = "Ihechikara"; switch (username) { case "Doe": System.out.println("Username is Doe"); break; case "John": System.out.println("Username is John"); break; case "Jane": System.out.println("Username is Jane"); break; default: System.out.println("Username not found!"); // Username not found! } } }

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

.

switch vs. if-else in Java
switch vs. if-else in Java

Keywords searched by users: java 11 switch case

How To Use Switch Case Statement In Java
How To Use Switch Case Statement In Java
Switch Statement In Java - Youtube
Switch Statement In Java – Youtube
Switch Statement In Java - Youtube
Switch Statement In Java – Youtube
Java Switch - Javatpoint
Java Switch – Javatpoint
Java Challenge #4: Switch Case
Java Challenge #4: Switch Case
Switch Statements In Java - Geeksforgeeks
Switch Statements In Java – Geeksforgeeks
Java Tutorial - How To Use Nested If'S And Switch Cases - Youtube
Java Tutorial – How To Use Nested If’S And Switch Cases – Youtube
Java Switch Statement | Important Concept
Java Switch Statement | Important Concept
P10 Switch Case Statement Beginner Java & Ap Computer Science - Youtube
P10 Switch Case Statement Beginner Java & Ap Computer Science – Youtube
Solved Switches: The Switch Statement Is Available In Many | Chegg.Com
Solved Switches: The Switch Statement Is Available In Many | Chegg.Com
Switch Statement Trong Java - Hướng Dẫn Java
Switch Statement Trong Java – Hướng Dẫn Java
Các Cải Tiến Của Java Cho Switch Statement Từ Java 12 | Topdev
Các Cải Tiến Của Java Cho Switch Statement Từ Java 12 | Topdev
Mệnh Đề Switch-Case Trong Java - Gp Coder (Lập Trình Java)
Mệnh Đề Switch-Case Trong Java – Gp Coder (Lập Trình Java)
Java Switch Statement | Switch Case Multiple Values Example - Eyehunts
Java Switch Statement | Switch Case Multiple Values Example – Eyehunts
Java Switch Case String | Digitalocean
Java Switch Case String | Digitalocean
Nested Switch Case - Geeksforgeeks
Nested Switch Case – Geeksforgeeks
What Is Switch Case In Java And How To Use Switch Statement In Java |  Simplilearn
What Is Switch Case In Java And How To Use Switch Statement In Java | Simplilearn
Loops, Switch Statements, And If-Else Statements In Java - Grooming Urban
Loops, Switch Statements, And If-Else Statements In Java – Grooming Urban

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *