Java switch and strings

Java switch Statements

A Java switch statement enables you to select a set of statements to execute based on the value of some variable. This is in effect somewhat similar to a Java if statement, although the Java switch statement offers a somewhat more compressed syntax, and slightly different behaviour and thus possibilities. In this Java switch tutorial I will explain both how the original Java switch instruction works, as well as the modifications to the switch instruction with the ability to switch on Java enums, Java Strings, and finally the new switch expression syntax that was added in Java 12 and improved in Java 13.

Java Switch Video Tutorials

If you prefer video, I have created two videos that explain the basic Java switch statement and the Java switch expressions.

Java Switch Statement Example

Let us start with a Java switch statement code example:

int amount = 9; switch(amount) < case 0 : System.out.println("amount is 0"); break; case 5 : System.out.println("amount is 5"); break; case 10 : System.out.println("amount is 10"); break; default : System.out.println("amount is something else"); >

This switch example first creates a variable named amount and assigns the value 9 to it.

Читайте также:  Run python from env

Second, the example «switches» on the value of the amount variable. Inside the switch statement are 3 case statements and a default statement.

Each case statement compares the value of the amount variable with a constant value. If the amount variable value is equal to that constant value, the code after the colon (:) is executed. Notice the break keyword after each statement. If no break keyword was place here, the execution could continue down the rest of the case statements until a break is met, or the end of the switch statement is reached. The break keyword makes execution jump out of the switch statement.

The default statement is executed if no case statement matched the value of the amount variable. The default statement could also be executed if the case statements before it did not have a break command in the end. You don’t need a default statement. It is optional.

The if Statement Equivalent

The Java switch example shown in the beginning is equivalent to the following set of Java if statements:

int amount = 9; if (amount == 0) < System.out.println("amount is 0"); >else if(amount == 5) < System.out.println("amount is 5"); >else if(amount == 10) < System.out.println("amount is 10"); >else

While it looks almost the same, there are situations where using a Java switch statement is easier, and faster. Also, the new Java switch expression added in Java 12 (see later in this tutorial) makes some constructs possible with a switch statement that are not possible with an if-statement.

Switch on Parameters

In the example shown in the beginning of this Java switch tutorial we declared an int variable and immediately set is value to 9. In a real life Java application you would most likely not do that. Instead you would be switching on the value of an input parameter of a method, or on a value read from a file, over the network etc. Here is an example of switching on a method parameter:

private static void switchOnIntegers(int size) < switch(size) < case 0 : < System.out.println("size is small"); break; >case 1 : < System.out.println("size is medium"); break; >case 2 : < System.out.println("size is large"); break; >case 3 : < System.out.println("size is X-large"); break; >default : < System.out.println("size is not S,M,L or XL: " + size); >> >

Switch on byte, short, char, int, String, or enum’s

As you have seen, the switch statement switches on a variable. Before Java 7 this variable has to be numeric and must be either a byte , short , char or int . From Java 7 the variable can also be a String It is also possible switch on a Java enum variable. In the following sections I will show you examples of how to switch on various different Java types.

Switch on byte, short and int

You can switch on a Java byte , short or int as shown in the following examples:

private static void switchOnIntegers(byte size) < switch(size) < case 0 : < System.out.println("size is small"); break; >case 1 : < System.out.println("size is medium"); break; >case 2 : < System.out.println("size is large"); break; >case 3 : < System.out.println("size is X-large"); break; >default : < System.out.println("size is not S,M,L or XL: " + size); >> >
private static void switchOnIntegers(short size) < switch(size) < case 0 : < System.out.println("size is small"); break; >case 1 : < System.out.println("size is medium"); break; >case 2 : < System.out.println("size is large"); break; >case 3 : < System.out.println("size is X-large"); break; >default : < System.out.println("size is not S,M,L or XL: " + size); >> >
private static void switchOnIntegers(int size) < switch(size) < case 0 : < System.out.println("size is small"); break; >case 1 : < System.out.println("size is medium"); break; >case 2 : < System.out.println("size is large"); break; >case 3 : < System.out.println("size is X-large"); break; >default : < System.out.println("size is not S,M,L or XL: " + size); >> >

Notice that the only thing that is different between the above examples is the data type of the method parameter size . Everything else is the same.

Switch on char

It is also possible to switch on a Java char value. Here is an example of switching on a char parameter:

private static void switchOnChars(char size) < switch(size) < case 'S' : < System.out.println("size is small"); break; >case 'M' : < System.out.println("size is medium"); break; >case 'L' : < System.out.println("size is large"); break; >case 'X' : < System.out.println("size is X-large"); break; >default : < System.out.println("size is not S,M,L or XL: " + size); >> >

Switch on String

From Java 7 and forward it is possible to use switch on a Java String too. Here is an example of a Java switch on a String :

private static void switchOnStrings(String size) < switch(size) < case "S" : < System.out.println("size is small"); break; >case "M" : < System.out.println("size is medium"); break; >case "L" : < System.out.println("size is large"); break; >case "XL" : < System.out.println("size is X-large"); break; >default : < System.out.println("size is not S,M,L or XL: " + size); >> >

Switch on Java Enum

It is also possible to switch on a Java enum. Here is a Java example that creates a Java enum and then uses it in a switch statement:

public class SwitchOnEnum < private static enum Size < SMALL, MEDIUM, LARGE, X_LARGE >private static void switchOnEnum(Size size) < switch(size) < case SMALL : < System.out.println("size is small"); break; >case MEDIUM : < System.out.println("size is medium"); break; >case LARGE : < System.out.println("size is large"); break; >case X_LARGE : < System.out.println("size is X-large"); break; >default : < default : < System.out.println("size is not S,M,L or XL: " + size); >> > > >

Multiple case statements for same operation

In case you want the same operation executed for multiple case statements, you write it like this:

Notice how the first case statement does not have any operation after the colon. The result of this is, that execution just «falls through» to the operation of the next case statement ( and the next etc.) until a break is met. The next break statement is after the second case statement. That means, that for both the first and second case statement, the same operation is executed — that of the second case statement.

Multiple Values Per Case Statement

From Java 13 and forward you can also have multiple values per case statement, instead of having multiple case statements falling through to the next. Here is the example from the previous section rewritten to use multiple values in a single state statement:

Notice how the multiple values for the first case statement are separated by a comma.

Java switch Expressions

Java 12 added the switch expression as experimental feature. A Java switch expression a switch statement which can return a value. Thus, it can be evaluated as an expression, just like other Java expressions (which are also evaluated to a value). In this section I will show you how the Java switch expressions of Java 12 works.

Remember, I have a video version of the Java switch expression part of this tutorial here:

Here is first a Java switch expression example:

int digitInDecimal = 12; char digitInHex = switch(digitInDecimal) < case 0 ->'0'; case 1 -> '1'; case 2 -> '2'; case 3 -> '3'; case 4 -> '4'; case 5 -> '5'; case 6 -> '6'; case 7 -> '7'; case 8 -> '8'; case 9 -> '9'; case 10 -> 'A'; case 11 -> 'B'; case 12 -> 'C'; case 13 -> 'D'; case 14 -> 'E'; case 15 -> 'F'; default -> '?'; >; System.out.println(digitInHex);

This Java switch expression example converts a value between 0 and 15 to a hexadecimal digit character.

Notice how the colon ( : ) after each case statement has been replaced with a -> operator. This operator is used inside of switch expressions to signal to the Java compiler that this case statement selects a return value for the switch expression, rather than selecting a block of code to execute.

Notice also, that the case statements have no break keyword after them. Since the value selected with the -> operator is interpreted as the return value of the switch expression, the break after each statement is implicit (unnecessary actually). You can also think of the -> as a return statement which returns a value from the switch expression, and thus breaks the execution of the switch expression.

Finally, notice how the digitInHex variable is assigned the return value of the switch expression. This is how you capture the output of a Java switch expression. You could also have returned its value as a return value from a method, like this:

public char toHexDigit(int digitInDecimal) < return switch(digitInDecimal)< case 0 ->'0'; case 1 -> '1'; case 2 -> '2'; case 3 -> '3'; case 4 -> '4'; case 5 -> '5'; case 6 -> '6'; case 7 -> '7'; case 8 -> '8'; case 9 -> '9'; case 10 -> 'A'; case 11 -> 'B'; case 12 -> 'C'; case 13 -> 'D'; case 14 -> 'E'; case 15 -> 'F'; default -> '?'; >; >

The Java switch expression also works with Java String values. Here is a Java switch expression example using Strings to switch on:

String token = "123"; int tokenType = switch(token) < case "123" ->0; case "abc" -> 1; default -> -1; >;

This example resolves a token type (integer value) based on the values of a String token.

Java switch yield Instruction

From Java 13 you can use the Java switch yield instruction to return a value from a Java switch expression instead of using the arrow operator ( -> ). Here is an example of the Java switch yield instruction looks:

String token = "123"; int tokenType = switch(token) < case "123" : yield 0; case "abc" : yield 1; default : yield -1; >;

switch Expression Use Cases

The Java switch expressions are useful in use cases where you need to obtain a value based on another value. For instance, when converting between number values and characters, as shown in the example above.

Java switch expressions are also useful when parsing characters into values, or String tokens into integer token types. In general, whenever you need to resolve one value to another.

Источник

The switch Statement

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.ArrayListfutureMonths = 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:

Using Strings in switch Statements

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 8 .

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.

Источник

Оцените статью