Overview of control (flow) statements in Java
Lesson content
- Implementation of algorithmic structures in Java - the control (flow) statements
- Overview of branching statements: if, switch
- Overview of looping statements (so-called loops): for, while, do-while, for-each
Implementation of algorithmic structures in Java - the control (flow) statements
Any sequence of Java commands written within the body of a method (a block of statements) actually represents an algorithm (i.e., its implementation in Java). So, how are specific algorithmic structures (sequential, branching, looping) implemented in Java?
Java commands from previous examples are executed strictly in the order in which they are written – “top to bottom”. This effectively represents the implementation of the sequential algorithmic structure in Java, and it is very simple. It’s enough to write the commands “one below the other”, and they will be executed sequentially in that order. If a method within this block calls another method, the commands in that called method will also be executed “top to bottom”, as if they were directly written in the calling method.
However, the implementation of branching and looping algorithmic structures in Java is achieved using special statements known as control (flow) statements, which are divided into two groups depending on the structure they implement:
-
Conditional branching statements (implement the branching algorithmic structure):
- if statement
- switch statement
-
Looping statements (implement the looping algorithmic structure, also known as “loops”):
- for statement
- while statement
- do-while statement
- for-each statement (covered in the chapter on arrays)
It is common for algorithms to contain combinations of multiple algorithmic structures, so control statements can be freely combined as needed.
Below is a brief overview of these statements with descriptions and simple examples. Each of these statements is explained in detail in the following lessons.
The if statement
The if statement implements conditional branching in Java when there are only two branches based on a condition:
- A branch that executes when the condition is true
- A branch that executes when the condition is false
Example 1
Create a class TemperatureCheck that has:
- A method checkTemperature that takes water temperature as a parameter and prints whether the water is warm enough for swimming (it must be greater than 22°C).
1 class TemperatureCheck {
2
3 void checkTemperature(double temperature){
4 if (temperature > 22)
5 System.out.println("The water is warm enough to swim");
6 else
7 System.out.println("The water is too cold to swim");
8 }
9 }
Create a class TestTemperatureCheck that in its main method checks if water temperatures of 19°C and 25°C are warm enough for swimming.
1 class TestTemperatureCheck {
2
3 public static void main(String[] args) {
4 TemperatureCheck tc = new TemperatureCheck();
5
6 tc.checkTemperature(19);
7
8 tc.checkTemperature(25);
9 }
10 }
The switch statement
The switch statement is used when there are more than two branches. The branching condition is based on the value of a variable, and each branch corresponds to a specific value.
Example 2
Create a class GradeCheck that has:
- A method checkGrade that takes a student grade (1 to 5) and prints its name: 5 - excellent, 4 - very good, 3 - good, 2 - sufficient, 1 - insufficient.
1 class GradeCheck {
2
3 void checkGrade(int grade){
4 switch (grade){
5 case 5: System.out.println("excellent");break;
6 case 4: System.out.println("very good");break;
7 case 3: System.out.println("good");break;
8 case 2: System.out.println("sufficient");break;
9 case 1: System.out.println("insufficient");break;
10 default: System.out.println("The grade must be in range 1-5");
11 }
12 }
13 }
Create a class TestGradeCheck that tests grades 5 and 3 in the main method.
1 class TestGradeCheck {
2
3 public static void main(String[] args) {
4 GradeCheck gc = new GradeCheck();
5
6 gc.checkGrade(5);
7
8 gc.checkGrade(3);
9 }
10 }
The for statement
The for statement implements a looping structure when the number of repetitions is known. It uses a loop counter to control the number of iterations.
Example 3
Create a class Printer with:
- A method printHello that prints the word “Hello” ten times.
1 class Printer {
2
3 void printHello(){
4 for (int i=1; i<=10; i++)
5 System.out.println("Hello");
6 }
7 }
Create a class TestPrinter that calls the above method.
1 class TestPrinter {
2 public static void main(String[] args) {
3 Printer p = new Printer();
4
5 p.printHello();
6 }
7 }
The while statement
The while statement implements a loop when the number of iterations is not known in advance. The loop runs as long as the condition is met, and the condition is checked before each iteration.
Example 4
Create a class InterestCalculator with:
- A method duplicationOfMoney that takes an investment amount and an annual interest rate (e.g., 12.5%). It prints the account balance after each year until the amount is doubled, assuming compound interest.
1 class InterestCalculator {
2
3 void duplicationOfMoney(double investmentAmount, double interestRate){
4 double total = investmentAmount;
5
6 while (total < investmentAmount * 2){
7 total = total * (100.0 + interestRate)/100.0;
8 System.out.println(total);
9 }
10
11 }
12 }
Create a class TestInterestCalculator that tests the above method with an investment of 20,000 dollars at 10% interest.
1 class TestInterestCalculator {
2
3 public static void main(String[] args) {
4 InterestCalculator ic = new InterestCalculator();
5
6 ic.duplicationOfMoney(20000, 10);
7 }
8 }
The do-while statement
The do-while statement is similar to while, but the condition is checked after each iteration. This ensures that the loop always executes at least once.
Example 5
Create a class InterestCalculator2 with the method duplicationOfMoney from the previous example, but using do-while.
1 class InterestCalculator2 {
2
3 void duplicationOfMoney(double investmentAmount, double interestRate){
4 double total = investmentAmount;
5
6 do {
7 total = total * (100.0 + interestRate)/100.0;
8 System.out.println(total);
9 } while (total < investmentAmount * 2);
10
11 }
12 }
Create a class TestInterestCalculator2 that tests the method with an investment of 20,000 dollars at 10% interest.
1 class TestInterestCalculator2 {
2
3 public static void main(String[] args) {
4 InterestCalculator2 ic = new InterestCalculator2();
5
6 ic.duplicationOfMoney(20000, 10);
7 }
8 }
The for-each statement
The for-each statement is used for looping specifically over arrays or collections. It means “for each item” and executes the same statement(s) for every element in a collection.
Example 6
Create a class Student with:
- Attributes: name, surname, and allGrades (an array of integers from 1 to 5).
- A method printStudent that prints the student’s full name and all grades.
1 class Student {
2
3 String name;
4
5 String surname;
6
7 int[] allGrades;
8
9 void printStudent(){
10 System.out.println(name + ", " + surname);
11
12 for (int grade : allGrades)
13 System.out.println(grade);
14 }
15 }
Create a class TestStudent that, within its main method, creates a student named Mike Stone with grades 5, 4, 3, 4, 5, 5, and prints all of his data on the screen.
1 class TestStudent {
2
3 public static void main(String[] args) {
4 Student s = new Student();
5
6 s.name = "Mike";
7 s.surname = "Stone";
8 s.allGrades = new int[]{5, 4, 3, 4, 5, 5};
9
10 s.printStudent();
11 }
12 }