From the course: Oracle Java Certification: 2. Operators and Decision Statements

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Switch statements vs. nested if-else

Switch statements vs. nested if-else - Java Tutorial

From the course: Oracle Java Certification: 2. Operators and Decision Statements

Start my 1-month free trial

Switch statements vs. nested if-else

- [Instructor] Another decision structure is the Switch Statement. It allows us to compare a variable to a list of literal values, and execute code blocks selectively. It is almost equivalent to a sequence of if-then-else statements but the type of the variable is limited to a handful of types. It can be any primitive integer types such as byte, short, and end. It can also be char or enops. Since Java 7, it is also possible to switch on string values. This code example seems to switch on a character object and the literal values used in the cases are primitive char values. Would this code even compile? The code actually works as expected. It seems that we can compare character objects to char primitives with no problem in a switch statement. This is probably due to auto boxing. The second line in the output seems unintended. A closer look at the code shows that a break statement is missing at the end of the first…

Contents