Understanding the effect of break keyword in a switch case structure - Java programming tutorial
Coding River
Understanding the effect of break keyword in a switch case structure - Java programming tutorial
In this video, I will talk to you about the effect of the keyword break in a switch case structure. We already know that the break statement is used to exit a switch case structure. But, I will give you some more details about what we mean by that
We will use the same portion of code we saw in the previous video
char grade = ‘A’;
switch (grade) { case 'A': System.out.println("The grade is A."); break; case 'B': System.out.println("The grade is B."); break; case 'C': System.out.println("The grade is C."); break; case 'D': System.out.println("The grade is D."); break; case 'F': System.out.println("The grade is F."); break; default: System.out.println("The grade is invalid."); }
When we run this code, we could notice that each action statement was executed based on whether the selector matches the case value associated with it.
But, what will happen if we removed the keyword break from the code?
So, I will remove the keyword from the code and run
char grade = ‘A’;
switch (grade) { case 'A': System.out.println("The grade is A."); case 'B': System.out.println("The grade is B."); case 'C': System.out.println("The grade is C."); case 'D': System.out.println("The grade is D."); case 'F': System.out.println("The grade is F."); default: System.out.println("The grade is invalid."); }
Notice that all our action statements are being returned in the console except the default one
What has happened here is that The selector grade stores the character ‘A’ and that character matches the first case value then all the statements following will execute until a break statement is encountered. We can notice that, even though the value of the selector does not match any of the other case values, the statements associated with these case values will execute anyway
This is because we did not put the break statement in our code
But if I choose to add a break statement right after the first action statement And run Notice that only the action statement associated with the matched case value is executed
If put the break statement after the second action statement And run Notice that all the action statements contained between the matched case value and the break statement are executed
So, you need to know how to use this break statement well, in order to make sure that only the appropriate action statements are being executed whenever a selector matches with a case value
That’s it concerning the effect of the break statement in a switch case structure
Thanks for viewing, I hope this video was informative. Please do not forget to like and SUBSCRIBE to this channel. Let’s meet in the next video.
#codingriver #java #programming ... https://www.youtube.com/watch?v=Opio5OW_qC8
9280498 Bytes