Switch case statements in Java - Tutorial for Beginners
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 the selector in our switch case structure
Whenever the value stored in the selector grade matches against a specified case value, then the appropriate action statement associated with that case value is executed
When we store the character ‘A’ in the grade then we will get the first action statement in the console
If we store the character ‘B’ then the second action statement will execute
If we store the character ‘C’ then the third action statement will execute
If we store the character ‘D’ then the fourth action statement will execute
If we store the character ‘F’ then the fifth action statement will execute
But if we store a character such as ‘M’, that is not corresponding to any of the case values, then the default action statement will execute
Alright, guys, that’s it about the Switch case structure in the next video I will talk to you about the importance of using the break statement function in a switch case control strucuture
Thanks for viewing, I hope this video was informative.
Please do not forget to like and SUBSCRIBE to this channel for more.
Let’s meet in another video.
#codingriver
#java
#programming
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Switch case statements in Java - Tutorial for Beginners», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.