Part 12 – Nested Loop & Java Switch
July 28, 2020 1 min read

In the last article we discussed about Java loops. You can check that part using the link given below.
Nested Loop in java
If a loop exists inside the body of another loop, It’s called a nested loop. And also called as “loop inside loop”.
Let’s see an example.

Here a for loop is inside the body of another for loop. It should be noted that the variables using for the 2 loops should be different from one another as you can see in the above example. See the output given below.

Also keep in mind you can you can put one type of loop inside the body of another type of loop. For example, you can put while loop inside the body of a for loop.
Java Switch
Switch statement is used when we have number of options and we may need to perform a different task for each option.
Let’s see a simple switch case statement.

Output:

If you input the number 3 to the console when running the program, you can see the letters “A” and “B” are printed. That is because there is no “break” keyword between the cases. If you input the number 2 , you can see only the letter “B” is printed as it is the last case. Let’s see the same example with the “break” keyword.

Output:

Now you can see if you use the “break” keyword you can print the value that you wanted as per your choice.
Hope you guys had a better understand about nested loop and the switch statement. Next article will be on the topic Java Methods.
Thank you.


