• Statements

    Purposes of statements:

    Declaring variables and assigning values.

    Control whether code will be executed.

    Control how often code will be executed.

Statement's body terminated by ;

{statement};
Variable declaration:
int a;
Value assignment:
a = 33;
Combined declaration and assignment:
int a = 33;
Expression:
a - 4
Statement:
b = a - 4;

Notice the trailing ;.

a = b + 3; b = a - 4;

Discouraged by good coding practices:

  • Poor readability

  • Hampers debugging

Debugging multiple statements per line
double initialAmount = 34;
{ // first block
  final double interestRate = 1.2; // 1.2%
  System.out.println("Interest:" + initialAmount * interestRate / 100);
}
{ // second block
  final double interestRate = 0.8; // 0.8%
  System.out.println("Interest:" + initialAmount * interestRate / 100);
}
  • Defining scopes

  • Unit of work

  • if: Conditional block execution.

  • for / while: Repeated block execution.

  • Statements
    • ➟ The if conditional statement
double saving = 320.00;

if (1000 <= saving) {
  // Rich customer, 1,2% interest rate
  System.out.println(
    "Interest:" + 1.2 * saving / 100);
}
System.out.println("Done!");
Conditional block execution
Done!
if (booleanExpression)
  (block | statement)
  • Statements
    • ➟ The if conditional statement
      • ➟ if-then-else
double saving = 320.00;

if (1000 <= saving )  { 
  // Rich customer, 1,2% interest rate
  System.out.println(
     "Interest:" + 1.2 * saving / 100);
}  else { 
  // Joe customer, 0.8%
  // standard interest rate
  System.out.println(
    "Interest:" + 0.8 * saving / 100);
}
System.out.println("Done!");
Interest:2.56
Done!
if ... else
if (booleanExpression)
   (block | statement)
[else
   (block | statement) ] 

Use

if (4 == variable) ...

in favour of:

if (variable == 4) ... 
  1. Providing better display
  2. Comparing for equality

Branches containing exactly one statement don't require a block definition.

double initialAmount = 3200;

if (100000 <= initialAmount)
  System.out.println("Interest:" + 1.2 * initialAmount / 100);
else if (1000 <= initialAmount)
  System.out.println("Interest:" + 0.8 * initialAmount / 100);
else
  System.out.println("Interest:" + 0);
if ('A' == grade || 'B' == grade) {
   result = "Excellent";
} else {
   if ('C' == grade) {
      result = "O.k.";
   } else {
      if ('D' == grade) {
         result = "Passed";
      } else {
         result = "Failed";
      }
   }
}
Nested if ... else
  • Statements
    • ➟ The if conditional statement
      • ➟ Using else if
if ('A' == grade || 'B' == grade) {
   result = "Excellent";
} else if ('C' == grade) {
   result = "O.k.";
} else if ('D' == grade) {
   result = "Passed";
} else {
   result = "Failed";
}
Enhanced readability: if ... else if ...
        else
if (booleanExpression)
   (block | statement)
[else if (booleanExpression)
   (block | statement) ]* 
[else
  (block | statement) ] 
Replacing else if (...){...} by nested if ... else statements
import java.util.Scanner;

public class App {
  public static void main(String[] args){

    final Scanner scan = 
        new Scanner(System.in);
    System.out.print("Enter a value:");
    final int value = scan.nextInt();
    System.out.println("You entered "
       + value);
  }
}
Enter a value:123
You entered 123

See nextBoolean(), nextByte() and friends.

  1. Post modifying an exam's marking
  2. At the bar
  3. Roman numerals

Task: Convert day's numbers to day's names

1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday
final Scanner scan = new Scanner(System.in));
System.out.print("Enter a weekday number (1=Monday, 2=Tuesday,...) : ");

final int number = scan.nextInt();

if (1 == number) {
   System.out.println("Monday");
} else if (2 == number) {
   System.out.println("Tuesday");
   ...

} else if (7 == number) {
   System.out.println("Sunday");
} else {
   System.out.println("Invalid number " + number);
}
Leap years
  • Statements
    • ➟ The switch statement
...
switch(number) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    case 3: System.out.println("Wednesday"); break;
    case 4: System.out.println("Thursday"); break;
    case 5: System.out.println("Friday"); break;
    case 6: System.out.println("Saturday"); break;
    case 7: System.out.println("Sunday"); break;

    default: System.out.println("Invalid number " + number); break;
} ...
Enter a weekday number (1=Monday, 2=Tuesday,...) : 6
Saturday
switch(expression) {
[case value_1 :
    [statement]*
    [break;] ]
[case value_2 :
    [statement]*
    [break;] ]
  ...
[case value_n :
    [statement]*
    [break;] ]
[default:
    [statement]*
    [break;] ]
}
  1. Why break?
  2. Extending to month days
String month, season;  
...
// Since Java 7: String based case labels
switch(month) {
    case "March": case "April": case "May":
       season = "Spring"; break;

    case "June": case "July": case "August":
        season = "Summer"; break;

    case "September": case "October": case "November":
       season = "Autumn"; break;

    case "December": case "January": case "February":
       season = "Winter"; break;
    }
}
  1. Converting day's names to numbers.
  2. Day categories.
  3. Roman numerals, using switch
  • Integer types:

    • byte and Byte

    • short and Short

    • int and Integer

    • char and Character

  • String

  • enum types

  • Statements
    • ➟ Loops

Objective: Execute the same statement multiple times.

Solution: Copy / paste the statement in question:

System.out.println("Do not copy!");
System.out.println("Do not copy!");
System.out.println("Do not copy!");
System.out.println("Do not copy!");

Problem: Only works if number of repetitions is known at compile time.

System.out.print("Enter desired number of repetitions: ");
final int repetitions = scan.nextInt();
switch(repetitions) {
    case 5: System.out.println("Do not copy!");
    case 4: System.out.println("Do not copy!");
    case 3: System.out.println("Do not copy!");
    case 2: System.out.println("Do not copy!");
    case 1: System.out.println("Do not copy!");   }

Limited and clumsy workaround.

  • Statements
    • ➟ Loops
      • while
final int repetitions = scan.nextInt(); 
int loopCount = 0; 

while (loopCount < repetitions ) {
   System.out.println("Do not copy!"); 
   loopCount++; 
}
Do not copy!
Do not copy!
Do not copy!
A while loop
Code Execution
System.out.print("Enter repetitions: ");
final int repetitions = scan.nextInt();
int loopCounter = 0;

while (loopCounter++ < repetitions) {
   System.out.println("Do not copy!");
}
Enter repetitions: 3
Do not copy!
Do not copy!
Do not copy!
while (booleanExpression)
   (block | statement)
int threeSeries = 1;

while ((threeSeries *=3 ) < 100);

System.out.println(threeSeries);

Exercise: Guess resulting output.

  1. Generating square numbers
  2. Calculating factorial
int sum = 0, value;
do {
  System.out.print(
    "Enter value, 0 to terminate: ");
  value = scan.nextInt();
  sum += value;
} while (0 != value);
System.out.println("Sum: " + sum);
Enter value, 0 to terminate: 3
Enter value, 0 to terminate: 1
Enter value, 0 to terminate: 0
Sum: 4
A do ... while loop
do
  (block | statement)
while (booleanExpression);
  1. Even or odd?
  2. Square root approximation
  • Statements
    • ➟ Loops
      • for
int i = 0; 

while (i < 5 ) {
   ...
   i++; 
}

Declaring and initializing a loop termination variable.

Check for loop termination.

Loop progression control

Nice to have: More concise syntax

for (int i = 0 ; i < 5 ; i++ ) {
  ...
}
int i = 0; 

while (i < 5 ) {
   ...
   i++; 
}
for ( init ; booleanExpression ; update )
  (block | statement)
// i being defined within
// loop's scope

for (int i = 0 ; i < 3; i++) {
    System.out.println(i);
}
// Error: i undefined outside
// loop's body
System.out.println(i);
// i being defined in 
// «current» scope

int i; 
for (i = 0; i < 3; i++) {
    System.out.println(i);
}
System.out.println(i); // o.K.
for (int i = 0 ; i < 3; i++) {
    System.out.println(i);
}

// i undefined in outer scope
{ // Beginning block scope
  int i = 0;
  for (; i < 3; i++) {
    System.out.println(i);
  }
} // Ending block scope

// i undefined in outer scope
while ( expression )
  (block | statement)
for ( ;expression ;)
  (block | statement)

Observation: for (...) is more general than while(...).

Printing even numbers
for (int i = 1; i <= 2; i++) {
  for (int j = 1; j <= 3; j++) {
    System.out.print("(" + i + "|" + j + ") ");
  }
  System.out.println(); // newline
}
(1|1) (1|2) (1|3)
(2|1) (2|2) (2|3)
for (int i = 0; i < 6; i++) {
  for (int j = 0; j < i; j++) {
    System.out.print(i + j + " ");
  }
  System.out.println(); // newline
}
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
// What are i and j actually meant
// to represent?

for (int i = 0; i < 6; i++) {
  for (int j = 0; j < i; j++) {
     System.out.print(i + j + " ");
  }
  System.out.println();
}
// Improved code comprehension.

for (int row = 0; row < 6; row++) {
  for (int column = 0;
        column < row; column++) {
    System.out.print(
         row + column + " ");
  }
  System.out.println();
}
  1. Merry Xmas
  2. More fun with Xmas trees
  3. A basic square number table
  4. Tidy up the mess!
  5. HTML-ify me
  6. Auxiliary Example, part 1: A multiplication table
  7. Auxiliary Example, part 2: Avoiding redundant entries
  8. Creating a real square table
  9. Creating a sophisticated HTML version of your square table
  • Statements
    • ➟ Loops
      • for
        • ➟ Loops and calculations
final int LIMIT = 5;
int sum = 0;

for (int i = 1; i <= LIMIT; i++) {
    sum += i;
}

System.out.println("1 + ... + " + LIMIT + " = " + sum);
1 + ... + 5 = 15
  1. Display all summands
  2. Playing lottery
  3. Guessing numbers
  4. Smallest multiple
  5. Smallest multiple, purely algebraic solution
  6. Pythagorean triples
  7. Avoiding duplicates and gaining performance
  • Statements
    • ➟ Using automated tests.
Response to coding errors
public class AlarmClock {
  /** Given a day of the week encoded as 0=Sun, 1=Mon,...
   */
  static  public String alarmClock(int day, boolean vacation) {
    switch (day) {
      case 1:
         ...
    if (vacation) {
      return "off";
    } else {
      return "10:00"; ...
public class AlarmClockTest {
  @Test 
  public void test_1_false() {
         Assert.assertEquals( "7:00", AlarmClock.alarmClock(1, false));
  }                                                            
  ...                                                          
                          Expected result               Input parameter
  @Test                                                        
  public void test_0_false() {                                 
         Assert.assertEquals("10:00", AlarmClock.alarmClock(0, false));
  }  ...
public class AlarmClockTest {                    Input parameter
  @Test                                                  
  public void test_1_false() {                           
         final String result = AlarmClock.alarmClock(1, false);
                        ┗━━━━━━━━━━━━━━━┓
                                        
         Assert.assertEquals( "7:00", result);
  }                             
  ...                           
                    Expected result