Java Beginner: Lesson 9 - switch

In this lesson we will cover the switch statement. The switch statement same as if statement is a conditional statement, so it checks if a condition is fullfilled, but differently from if statement it is used for a well known set of values and for specific variables. If statement can be used to test complex conditions which can involve even more than one variable, while the switch statement is used to check the value of a specific variable.

Example code:

The example code above shows the structure of a switch statement in case we would test a string variable. So if the string variable with name variableToTest would have the value "value1" we would have as output the string "Variable 1 choonsen" else if the string variable with name variableToTest would have the value "value2" we would have as output the string "Variable 2 choonsen" else in case of another value in the string variable with name variableToTest we would have as output the string "Invalid input".

Bellow is shown the the full code of the switch statement shown above:

Example code:

In the figure 1 bellow is shown an execution of the example code with input "value1".


Figure 1: Switch case value1


In the figure 2 bellow is shwon the execution of the example code with input "a non predicted value to result in the default case", which as the input string indicates is a non predicted values in the body of the switch statement so it will execute the code under the default case.


Figure 2: Switch case default


(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game