Switch case and constant java

Java Flow Control: The switch Statement

Conditional statements and loops are a very important tool in programming. There aren’t many things we could do with code that can only execute line-by-line.

That’s what «flow control» means — guiding the execution of our program, instead of letting it execute line-by-line regardless of any internal or external factors. Every programming language supports some form of flow control, if not explicitly via if s and for s or similar statements — then it implicitly gives us the tools to create such constructs, i.e. low-level programming languages usually achieve that affect with a lot of go-to commands.

Loops were a concept used long before computer programming was even a thing, but the first person to use a software loop was Ada Lovelace, commonly known by her maiden name — Byron, while calculating Bernoulli numbers, back in the 19th century.

In Java, there are several ways to control the flow of the code:

The switch Statement

If we wish to compare a value to multiple values and execute code based on their equality, we could do something along the lines of:

String input = "someCommand"; if (input.equals("date")) < System.out.println("The current date is: " + new Date()); > else if (input.equals("help")) < System.out.println("The possible commands are. "); > else if (input.equals("list")) < System.out.println("The files in this directory are. "); > else if (input.equals("exit")) < System.out.println("Exiting application. "); > else < System.out.println("Command Not Supported"); > 

This can quickly become cumbersome and unreadable. The switch statement was introduced to us precisely to avoid this whenever possible. This statement is used when we have several different things that we want executed based on the value of a single expression:

switch(variable) < case constant1: // Do something if the variable is equal to constant1. // constant1 must be of same type as variable // or easily converted to, such as Integer -> int break; case constant2: // Some code break; . default: // Some code break; > 

The variable passed as the switch argument is the variable or expression whose value we are comparing. That value is compared to each of the case values. If the variable we’re checking matches any of the cases, the code following that case is executed. We can have as many case statements as we want.

There are four new keywords we’re introduced to here: switch , case , break , and default .

switch

The switch statement typically accepts a variable, though it can also accept an expression if it returns an accepted type:

// Comparing the value 5 with case values switch(5) < // Cases > int x = 5; int y = 10; // Comparing the value 15 with case values switch(x+y) < // Cases > // Booleans are not supported by switch statements, // so this won't compile switch(!true) < // Cases > 

If we pass a null value to the switch , a NullPointerException will arise.

case

The case label’s value must be a compile-time constant. This means that for all case values, we must either use literals/constants (i.e. «abc», 5, etc.) or variables that have been declared final and assigned a value:

final int i = 5; int y = 15; final int z; z = 25; int x = 10; switch(x) < case i: // i can't be changed at any point due to the // `final` modifier, will compile break; case y: // Won't compile as `y` isn't a compile-time constant break; case 10+10: // Compiles, as 10+10 is a compile-time constant break; case z: // Doesn't compile as z wasn't initialized with // its declaration, thus it isn't considered to // be a compile-time constant break; case null: // Doesn't compile, there can't be a null case break; > 

The cases must all be unique, otherwise Java the code won’t compile. If the cases weren’t unique, there would be no way to know which case to execute among the duplicate values.

Читайте также:  Unable to load mysql driver java

break

The break keyword is used to break the flow of the code within cases. Once the switch statement has found a case that matches the passed variable, it proceeds to execute case code until either the first break keyword is encountered or the end of the switch block itself.

int ourNumber = 1; switch(ourNumber) < case 1: System.out.println("One"); case 2: System.out.println("Two"); case 3: System.out.println("Three"); break; case 4: System.out.println("Four"); > 

The output of this code is:

In this example, the flow of execution «falls through» from the first case statement (which matched the ourNumber value) to the break statement.

This can sometimes lead to unwanted cases being executed, so we should be careful to add break statements, and a good idea is to add them by default in every case , and remove them later if we do want to execute multiple cases for some inputs. More info on the break statement can be found here.

If we did want the same code executed for multiple cases, this is a common pattern used:

. case "a": case "b": System.out.println("Variable is equal to constant1 or constant2!"); break; . 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This would execute the System.out.println line if our variable is equal to either «a» or if it’s equal to «b» .

default

The default case is a piece of code that switch executes if the variable we’ve passed to it doesn’t match any of the given cases. This statement is optional, though highly recommended to avoid situations where user-defined input breaks the whole flow of the application.

Accepted Data Types

The variable passed as a switch argument can be one of the following:

This is a huge jump from the if and else-if statements, which only support boolean expressions.

That being said, we can easily rewrite the if / if-else example from the beginning of this article:

 switch("someCommand") < case "date": System.out.println("The current date is: " + new Date()); break; case "help": System.out.println("The possible commands are. "); break; case "list": System.out.println("The files in this directory are. "); break; case "exit": System.out.println("Exiting application. "); break; default: System.out.println("Command Not Supported"); break; > 

Or, as another example, we could pass an integer and replace this chain of if and else-if blocks with a more readable counterpart:

int ourNumber = 4; if (ourNumber == 1) < System.out.println("One"); > else if (ourNumber == 2) < System.out.println("Two"); > else if (ourNumber == 3) < System.out.println("Three"); > else if (ourNumber == 4) < System.out.println("Four"); > else < System.out.println("Larger than 4"); > 

The equivalent switch statement would look like the following:

switch(ourNumber) < case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; case 3: System.out.println("Three"); break; case 4: System.out.println("Four"); break; default: System.out.println("Larger than 4"); break; > 

It’s clear that if ourNumber is equal to 1, the code after case 1: will be executed, and «One» will be printed to the standard output.

Читайте также:  Python list erase all

Note: Unlike other data types, Strings aren’t compared with the == operator, but with the .equals() method when checking against all the cases. This is done so that the actual value of the strings are compared, and not the memory location.

Nested switch Statements

We can nest multiple switch statements.

switch(var1) < case constant1: switch(var2) < // . > break; case constant2: . > 

Lambda Expressions

Java 12 has a new, more concise way of handling switch statements using Lambda Expressions.

By using switch statements in this way, breaks are no longer necessary, and returning a value is more readable. This is only available as a preview option currently. A typical new type of switch would look something like this:

switch(ourNumber) < case 7, 3, 8, 4 -> System.out.println("Very popular lucky number"); case 5, 13, 9, 6 -> System.out.println("Kind of popular lucky number"); default -> System.out.println("Not all that popular"); > // Or something like: String s = switch(ourNumber) < case 7, 3, 8, 4 -> "Very popular lucky number"; // . > System.out.println(s); 

Conclusion

Flow control in code is essential for absolutely every application. Statements that alter the flow of code are fundamental building blocks and every aspiring developer should be completely in control/aware of how they work.

Источник

Switch case and constant java

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.

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.

Читайте также:  Java oracle с чего начать

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.

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

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:

Because a switch expression must evaluate to a single value (or throw an exception), you can’t jump through a switch expression with a break , yield , return , or continue statement, like in the following example:

Источник

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