Java tutorial 5 - SWITCH STATEMENTS
In the last tutorial, we tried to understand how if else statements work. In this 5th tutorial, we will aim at understanding the concept of switch statements.
In case you haven't read the previous tutorial, I recommend you to first go through it and then continue with this one. I'll wait for you.
DRUM ROLL
So, what is a switch statement?
A switch statement is a multi-way branch statement.
Let's try to understand it with help of an example
int a=3;
switch (a){
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
default:
System.out.println("I don't know");
break;
}
Explanation
Here the output is dependent upon the value of a.
In case, the value of a is equal to 1, the output will be one.
Similarly, in case, the value of a is equal to 2, the output will be two.
Similarly, in case, the value of a is equal to 3, the output will be three.
And if none of them are true, the output will be "I don't know"
OUTPUT
three
As expected, the output is three.
And there we are
I think that you were able to understand how switch statements work. In case you have any doubts, I am happy to help you out.
In the next part, we will learn about while loops. Hope to see you there too.
That`s it for this blog. If you wanna become a great programmer, I am there to help.
You can see my profile by clicking on my name below.