Control Structures

In this part you will learn about conditional execution and loop constructs in Java.

If-then-else

The if statement allow conditional execution of code.

if (<condition>) {
    <body>
}

The <body> of the if statement is executed if <condition> evaluates to true. <condition> has to be an expression whose type is boolean.

else

The else statement allows code to be executed when the <condition> of the corresponding <if> statement fails.

if (<condition>) {
    // executed if condition evaluates to true
}
else {
    // executed if condition evaluates to false
}
In [1]:
int x = 17;

// print x if it is larger than 10
if (x > 10) {
    System.out.println(x);
}
17
Out[1]:
null
In [2]:
int x = 17;

// print different result depedening on whether x is smaller than 10 or not.
if (x < 10) {
    System.out.println("x is less than 10");
}
else {
    System.out.println("x is larger than or equal to 10");
}
x is larger than or equal to 10
Out[2]:
null
In [3]:
// a bank account balance
double balance = 4500.00;

// add 10% interest if current balance > 3000
if (balance > 3000.0) {
    balance *= 1.1;
}
// otherwise add 5% interest
else {
    balance *= 1.05;
}
return balance;
Out[3]:
4950.0

Switch statement

The switch statement in Java allows the execution of code based on the value of an expression:

switch (<expr>) {
    case <value1>:
        ...
    break;
    case <value2>:
    ...
    break;
    ...
    case <valueN>:
    ...
    break;
    default:
    ...
}

The result of <expr> which has to be an expression that evaluates to a primitive type or String is compared against the <value> of each case top-down. Once a matching value is found, the code until break is executed. If none of the cases applied the code under default is executed. Note that default is optional. The same applies for break. It is possible to have case without a break which can result reduced amount of code, but if considered bad practice by many because of hard to debug errors.

In [4]:
int x = 3;

switch (x) {
    case 1:
        return "1"; // no break needed because we return here
    case 2:
        return "2";
    case 3:
        return "3";
    default:
        return "None";
}
Out[4]:
3
In [5]:
// fall through case without break
String custType = "Premium";

// using fallthrough if a customer is premium, we also execute the code for basic customers
switch(custType) {
    case "Premium":
        System.out.println("is premium customer");
    case "Basic":
        System.out.println("has an account");
    break;
    default:
        System.out.println("Not one of our customers");
}
is premium customer
has an account
Out[5]:
null

Iterative Constructs

Java supports multiple iterative constructs (loops). A loop repeately executes a section of code. Each such execution is called an iteration.

While loop

The while loop repeatly executes its body until its condition (an expression of type boolean) is evaluates to false. The condition is evaluated before each execution of the loop.

while (<cond>) {
   ...   
}

Do-While loop

The only difference to the while loop is that the condition is evaluated after each iteration instead of before.

do {
 ...   
} while (<cond>)

For loops

A for loop in Java comes in one of two forms. In the first form, the loop consists of an <initialization>, a <condition>, and a <step>. The <initialization> is executed once before the loop starts. The <condition> is evaluated before every loop iteration and the loop stops once the condition evaluates to false. The <step> is evaluated after every loop iteration.

for(<initialization>; <condition>; <step>) {
    ...
}

A typical use of a for loop is to execute the loop body a given number of times which can be realized using a counter variable:

// this code is executed 10 times
for(int i = 0; i < 10; i++) {
   ... 
}

The second type of for loop in Java allows the iteration over a collection or arrays. A loop variable is declared and in every iteration is bound to an element from the collection/array until all elements have been processed.

String[] strs = { "A", "B", "C" };
for(String a: strs)
{
    ...
}
In [6]:
// use a while loop to iterate throug numbers 0 to 4
int i = 0;

while(i < 5) {
    System.out.println(i);
    i++; // increase the counter variable i by 1
}
0
1
2
3
4
Out[6]:
null
In [9]:
// use a do-while loop to iterate [0,...,4]
int i = 1;

do {
    System.out.println(i);
    i++; // increase the counter variable i by 1
} while(i < 5);
1
2
3
4
Out[9]:
null
In [10]:
// use a for loop to iterate through numbers 0 to 4
for(int i = 0; i < 5; i++) {
    System.out.println(i);
}
0
1
2
3
4
Out[10]:
null
In [7]:
import java.util.List;
import java.util.ArrayList;

// using for to iterate over an array and collection
String[] strs = { "Peter", "Bob" };

for(String s: strs)
    System.out.println(s);

List<String> l = new ArrayList<String> ();
l.add("Alice");
l.add("Jane");

for(String s: l)
    System.out.println(s);
Peter
Bob
Alice
Jane
Out[7]:
null

Note that in the example above we made use of the fact that for control statement that have a body that only consists of a single statement the use of {} is optional.

Visibility of variables

The scope of variables declared in a for statement is the body of the for statement.