Switch case statements in Java - Tutorial for Beginners
Coding River
Switch case statements in Java - Tutorial for Beginners
In this video, we will talk about switch case structures. In our previous videos, we said that there are three types of selection control structures in Java. We talked about the first two of these selection control, which are the if and the if … else statements
Now, the third selection control structure is called the Switch case structure One of its particularities is that it does not require the evaluation of a logical expression as compared to the if … else statements
The Switch case structure allows the computer to choose from multiple alternatives or options
Here on the screen, is the syntax of a switch case statement
char grade = ‘A’
switch (grade) { case 'A': System.out.println("The grade is A."); System.out.println("You are a first class student"); 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."); }
Let me explain the various elements in this statement First, let’s note that the words switch, case, break, and default in this statement are what we call in Java reserved words or keywords
Secondly, just after the keyword switch, is what we call the selector In a switch structure, the selector is evaluated first and its value is used to determine which action statements are selected for execution. The selector can be a variable or an expression Also, the value returned by the selector must only be of type int, byte, short or char So, if the selector is an expression, then it must return an integral value
Next, we have the keyword case and right after the keyword there is a value The value is making reference to the whatever value the selector may return Note that a specific case value must appear only once in a switch structure We cannot have two case values that are the same
Following the case value, we have a statement This statement will be executed if the value of the selector is equal to the case value We can have one or more statements associated with a case value So, we do not need to use curly braces to turn multiple statements into a single compound statement
Next, the keyword break is used to exit a switch case structure I will talk to you in much more details about the importance of this keyword in the next video
The keyword default is also not compulsory and it is used to determine the statements that will be executed whenever the selector value does not match any of the case values
So basically, in our example here is what is going to happen
We have declared a variable grade of a type character That variable grade is used as ... https://www.youtube.com/watch?v=Y5DQ6yeNSxg
10675322 Bytes