JAVA Basics #12 - Loops | Switch
Chathumi Kumarapeli
Posted on May 10, 2021
This article is on switch statements and loops.
Switch statement
Assume you have built a website and a user is trying to log into it. You are asking the user to enter his email. Then you are checking whether that email is stored in your database and if so you are fetching his user role (admin, blog writer, reader). If mail is not found the user is a guest. After that you want to print this user roles. To implement this you can easily use switch statements.
Look at the code block given below (Assume you have already fetched the user role from the database into a String variable named userole
).
switch (userRole) {
case "admin":
System.out.println("Hi you are an admin");
break;
case "blog writer":
System.out.println("Hi you are a blog writer");
break;
case "reader":
System.out.println("Hi you are a reader");
break;
default:
System.out.println("Hi you are a guest. Please register to log in.");
}
In here the first case checks whether the value of the userRole
is 'admin'. If so it will print "Hi you are an admin". You can see that I have added break
after the print statement. What break
does is that going out of the switch statements. Which means once a particular case is achieved, no other cases will be evaluated. You will simply go out of the switch block. Same process goes to the cases 'blog writer' and 'reader'.
Next comes the case where you were unable to find the email in the database. Therefore that email does not have a userRole
yet. SO by default
the last case will print the 'guest' statement. There we have not used break
. This is because, default
is the last case in the switch block. So it will automatically go out of the switch block. No break
statement is required here. This might be a bit messy to understand but once you get used to it applying switch statements will become handy.
Loops
for Loop
Think that you want to print numbers from 1 to 5. Then you will think that you have to write pritln()
line 5 times. But what if you have an opportunity to write just one println()
and iterate it 5 times? Sounds great right. Let's see how we can do that.
for (int i = 1; i <= 5; i++)
System.out.println(i);
Let's evaluate the code. We have use iterations here by using a 'for loop'. As you can see I have declared a variable i
inside the parenthesis of the for()
. After that we have give the range for 'i'. Here we want to print numbers from 1 to 5. Therefore i
has to be iterated from 1 to 5. So I have mentioned as i = 1
and after a semi colon (;) I have stated that i <= 5
. This means i
goes from 1 to 5. You also can write it as for (int i = 1; i < 6; i++)
. Here also you can get same output. Inside 'for()' loop you have to write the code lines that has to be executed. Here since we are only writing a single code line, we need not to use curly braces.
For loops are used in situations where the number of the iterations are known before hand.
Task
Given an array, books = {"Twilight", "New moon", "Eclipse", "Breaking dawn", "Safe Heaven", "Kite Runner", "Hunger Games"} print all its elements using a for loop.
How did you code the above task? Let me guess. I assume that, you entered a range in a for loop like (int i=0; i<7; i++) and print the elements by calling the index. However, there is an easier way of doing the same task. Check out this code.
String[] books = {"Twilight", "New moon", "Eclipse", "Breaking dawn", "Safe Heaven", "Kite Runner", "Hunger Games"};
for (String book : books)
System.out.println(book);
Here the string book
in the parenthesis refers to a single element in the array books
. Therefore, this will print all the elements in the books
array accurately. The negative side of this method is that you can only iterate from beginning to the end. Like you cannot get the output as Hunger Games, Kite Runner, ... Twilight (from right to left) order. And also since you do not have access to index, you won't be able to know the index value of a particular element when you use this method.
While Loop
What if you do not know the number of the iterations beforehand? Then you can use 'while loop'. Check the below code;
int i = 0;
while(i < 10) {
System.out.println(i);
i++;
}
In the above code we first declared an integer variable i
and initialized it into zero. The code line while(i<10)
ensures that the value of i
is always less than 10. Which means the code inside the while()
loop will only execute if the i
is less than 10. Then we print i
and increment it by one.
While loops can be used in conditions where you does not know the number of iterations beforehand.
Assume in a case where you want user to add subject names, but you do not know number of subjects that are available. What can you do in such a scenario? You have to use a 'while loop' as you do not know the number of iterations here. You can ask the user to enter some word like 'quit' or 'finish', if he has entered all the subjects. Then you can make the loop run only when the input word is not equal to the termination word. Go through the below code.
Scanner userInput = new Scanner(System.in);
String input = "";
int count = 0;
while (!input.equals("quit")) {
System.out.print("Subject: ");
input = userInput.nextLine().toLowerCase();
count += 1;
}
int subjectCount = count - 1;
System.out.println("Number of subjects = " + subjectCount);
In above code we have taken user input as a Scanner
class object, and then has read the line and has stored into the string input
. Here you can see that I have used the method toLowerCase()
. Why do we need that? Look at the condition inside the parenthesis of the while loop. What it means that the value stored in input
string cannot be equal to 'quit'. All the letters in 'quit' is in lowercase. Therefore, if user entered like 'Quit' or 'QUIT' the loop will not terminate. So to avoid those disconcerts we have to convert the user input into lowercase.
do while loops
There is only one deference in 'do-while' loop when compared to 'while' loops. In while loop, statements will execute if and only if the condition given in the loop is true. But in 'do-while' loops statements gets executed once before checking the conditions given for the loop. Check the following code.
int i = 0;
do {
System.out.println(i);
i++;
} while(i < 10);
Here, first println()
method gets executed and print '0'. After that it will increment it value to 1. Then only the condition in while loop is taken under consideration. Because of this we can say that 'do-while' loops will definitely execute 'at least' only once.
And with that we can wrap up this article :)
Posted on May 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.