
Since Java 7, you can use strings in the switch statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. You cant miss a switch case (you can incorrectly implement a method for a particular constant, but theres nothing that will ever totally prevent that from. The Java switch statement executes one statement from multiple conditions. You might consider using polymorphic method dispatch with Java enums rather than an explicit switch. 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 type 1. SwitchDemoFallThrough shows statements in a switch block that fall through. You actually can switch on enums, but you cant switch on Strings until Java 7. Unlike the if/else if/else statement, a switch statement can have a number of possible execution paths. 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. Control flow continues with the first statement following the switch block.

Each break statement terminates the enclosing switch statement. 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.Īnother point of interest is the break statement.

You could also display the name of the month with if-then-else statements:ĭeciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. 11 Answers Sorted by: 88 Assigning a value to a local variable and then returning that at the end is considered a good practice. The switch statement evaluates its expression, then executes all statements that follow the matching case label. A statement in the switch block can be labeled with one or more case or default labels. The body of a switch statement is known as a switch block. In this case, August is printed to standard output.
