From the course: Java 8 Essential Training

Unlock the full course today

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

Using the switch statement

Using the switch statement - Java Tutorial

From the course: Java 8 Essential Training

Start my 1-month free trial

Using the switch statement

- The if and else keywords give you complete flexibility in writing conditional code. But you can sometimes write conditional code more efficiently using the switch statement. A switch statement examines a single value and then compares it to multiple possibilities, and you can control the flow of execution based on when the two values match. I have code in place to collect a value from the user. I then parse that value as a primitive int. I'll run the code for the first time and show that in the run window I can click here, type in a number, and then the application finishes, but nothing else happens. My goal is to examine that value. I'll place the cursor after the existing code and I'll add the switch keyword. IntellJ IDEA adds parentheses. Place the value you want to examine within the parentheses. I'll place the value monthNumber. Then add a pair of braces, that's the switch code block. Now within the switch code block, you can have one or more cases. Each starts with the word…

Contents