![]() This saves time on execution because the program doesn’t need to evaluate more cases after the right case has been found. This statement is important because it stops a program from testing for more cases when a case has already been met. When Java executes a break statement, it’ll stop running the code within the switch block and continue running the program. In our code above, we used the break keyword. If it was May, for example, the month value would be 5, and so May would be printed to the console. Then, our program prints out the name of the month to the console and executes a break statement, which stops our program from continuing. In this case, the case 2 statement evaluates to true, because it’s February, which has the numeric value 2. The program executes each case one-by-one until it finds one that evaluates to true. Then, we define a switch statement that has six cases. At the start, we use the LocalDate method to get the numeric value, which represents this month. When we execute our code, the following response is returned: February. Here’s the code we can use to retrieve this data: The number 1 represents January, 2 represents February, and so on.īefore we begin, we’ll first need to set up the code that gets the numeric value corresponding to this month. To create this program, we’ll use the time.LocalDate Java method to get the numeric value corresponding to this month. We only want our program to work with the first six months of the year. Let’s say we want to create a program that tells us the name of the month based on the numeric value of the month. ![]() ![]() We’ll walk through a working example of the switch statement to illustrate how it works. If none of our conditions evaluate to true, the contents of the default statement will be executed. If an expression does not match a case, the subsequent case label will be evaluated. If the expression matches a case, the block of code associated with the case statement is executed. Then, the value of the expression is compared with the values of each case, starting from the top of the switch statement. The expression contained in the switch statement is evaluated once.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |