In this course, we look at control flow statements in the Java programming language.
Learning Objectives
- Decision-making statements
- Looping statements
- Branching statements
Intended Audience
- Anyone looking to get Oracle Java Certification
- Those who want to learn the Java Programming language from scratch
- Java developers who want to increase their knowledge
- Beginners with no previous coding experience in Java programming
- Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams
Prerequisites
- No prior knowledge is required about the Java programming language.
- Basic computer knowledge
Hi there. In this video we're going to learn to use switch case statements and understand how to control the flow of our program's execution. The switch case statement executes one statement from multiple conditions. It's like the if-else if ladder statement that you learned in the previous video. The switch case statement works with primitive data types, such as byte, short, int, and long. It also works with strings and enum types that we will discuss in the next lectures. As you see in the diagram, the switch case statement starts with the switch keyword and conditional expression between brackets. If case condition 1 is true, Code Block 1 is executed.
If case condition 1 is false and case condition 2 is true, Code Block 2 is executed. If case condition 1 is false and case condition 2 is false, if case condition n is true, Code Block N is executed. If all case conditions are false, the default code is executed. There are important points to using the switch statement. There can be one or n number of case values for a switch expression. The case value must be of switch expression type only. The case value must be literal or constant. We cannot use variables. Also, one of the new features added in Java SE7 is the capability to switch on a string. The case values must be unique, in case of duplicate value, compile time error exits. Each case statement can have a break statement.
A break statement is not mandatory, it's optional. The break statement means to terminate the flow and exit the switch block after the relevant condition is met. If you do not use the break keyword you will not get an error, but the program will continue until it encounters a break or until the end of the switch block. Don't forget this. As a result, when control reaches the break statement it jumps the console after the switch expression. If a break statement is not found it executes the next case. Let's move on to the eclipse and make some practice. In exercise project, right click on the decision making package and select new class. Specify the class name as switch case statement and select the checkbox for the main method. Before coding let's move the console panel to the right side of the screen to view code examples comfortably.
You can do this just by dragging and dropping this view to this area. It seems very nice. Let's start. We will make a simple example explaining the switch case structure. We'll enter a number in the console, and as a result it will give us the day of the week corresponding to that number. We will do this first with the if-else and then with the switch case, so you can better understand the difference. First, we need to import the scanner class for getting input from the user, Scanner number = new Scanner (system.in). We choose the import scanner class in java.util package to import the scanner class. We show a message to enter a day number of weeks by using the print method, System.out.printin "Please enter a day number of the week". And we declare a variable day number with int type and design the next int method of the scanner class to this variable.
Also, I'll declare a variable day with string type. First, let's start to write the if-else statement. If(dayNumber == 1). I'll assign Monday to the variable day and I will create the else-if statement, If(dayNumber == 2). I will assign Tuesday to the variable day. Now I will copy this else-if statement and paste it below five times. The second else-if will be three and the day will be Wednesday. The third else-if will be four and the day will be Thursday. The fourth else if will be five and the day will be Friday. The fifth else if will be six and the day will be Saturday. The last else-if will be seven and the day will be Sunday. We have seven days in a week. So, if the user enters a number that is greater than seven, we should warn the user by using the else block. In the else part we assign 'invalid day choice' to the variable day.
Let's display the value of day by using the print method. Don't forget to close the scanner object by using the close method. Let's run the code. We enter three for the day number of the week. Second else-if, i.e, condition 3, is executed and 'the day is Wednesday' method is displayed. Let's run the code again and enter five. Fourth else-if is executed and the 'day is Friday' message is displayed. Finally, run the code and enter eight. So, this time the else block is executed and the 'invalid day choice' message is displayed. Yes friends, this is the if-else statement. Now let's develop this app using the switch case statement. First, I will convert these codes to the comment line. Now, let's continue.
The conditional switch expression is the day number. In the first case we assign Monday to the variable day and use the break keyword. Let's copy the code and paste it below seven times. Now let's make changes for case values and other days of the week. The second case will be two and the day will be Tuesday. The third case will be three and the day will be Wednesday. We also use the break keyword in each case condition because we don't want to execute each case condition. The fifth case will be five and the day will be Friday. The sixth case will be six and the day will be Saturday. The seventh case will be seven and the day will be Sunday. Also, we have seven days in a week, so if the user enters a number that is greater than seven, we should warn the user by using the default keyword. In the default part we assign 'invalid day choice' to the variable day.
Let's display the value of day by using the println method. Let's run the code. We enter three for the day number of the week. Case condition 3 is executed and the 'day is Wednesday' message is displayed. Let's run the code again and enter five. Case condition 5 is executed and the 'day is Friday' message is displayed. Finally, run the code and enter eight. The default part of the switch statement is executed and the 'invalid day choice' message is displayed. The switch case statement works like that. Now, I'll convert the comment line to the last three break keywords to show you the difference. Also, I'll cut this print method and paste it into the 5th, 6th and 7th cases.
Otherwise, the last value of the day string always will be invalidate choice, because lastly the default case will run. Now, if I enter '6' to the console, the last three messages will be displayed on the console, because after the sixth case, there is no break keyword, and the compiler doesn't exit from the switch case statement until the end of the code. Let's run and see. I enter '6'. As you can see, the last three cases were executed because there is no break keyword.
Now I'll delete these comment lines. And let's run the code again. Now I will enter the '6' again. And as you can see, this time, only the sixth case was executed. I think the usage of the switch-case statement is understood. So, when can we use or not use the break keyword? If there's a situation where we wanted to give the same result in more than one situation, it may be more logical not to use the 'default' keyword here. For example, if the number entered by the user corresponds to a weekday, let's print weekday in the console. If it corresponds to the weekend, let's print the weekend this time. Let's turn the codes here into comments. Now, let's create the switch-case statement. I'll check the day number again. This time, the 1st, 2nd, 3rd, 4th and 5th cases must return the same result. For this reason, I will not use the break keyword for each case, and I'll assign the result to the day string only once. I write 'case 1:, case 2:, case 3:. You can also write the cases like that, case 4:, case 5.
Now, let's assign the weekday to the day string. And only use the break keyword here. Now, let's check the 6th and 7th cases. Case 6:, case7:. Now let's assign the weekend to the day string. And I'll use the break keyword here. And lastly, I'll use the 'default' case. And to sign the 'invalid day' choice to the day string. And I will also use the break keyword here. And let's print the result to the console. Yes. Now let's run and test. I'll enter '3'. So, the result is 'weekday'. I will run again, and enter '5'. The result is the same. I'll run again in enter '6' this time, the result is the 'weekend'. I'll run again, and enter '7' this time. So the result is the weekend. And lastly, I'll enter 10. This time the default case was executed and the result is 'invalidate day choice'.
Excellent. Lastly, I'll show you another thing and finish the lesson. You can also use the if-else statement inside the switch case. For example, if the user enters the '3', let's show this message. 'Weekday Wednesday', else 'weekday other days'. Let's run and see. I enter '3'. So, the if block was executed, and the result is 'weekday, Wednesday'. I'll run the app again. This time, I will enter '1'. As you can see, this time the output is 'weekday, other days'.
Yes friends, this is how the switch-case statement is used. I hope it was useful for you. Let's take a short break here. See you in the next lesson.
OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.