Overview

  • Statements

    Lecture notes

Purposes of statements

  • Declaring variables and assigning values.

  • Creating output.

  • Control whether code will be executed.

  • Control how often code will be executed.

Lecture notes

  • Statements

Create comment

General Syntax

Statement body terminated by ;

{statement};

Lecture notes

  • Statements

Create comment

Example: Declaring and assigning variables

Variable declaration
int a;
Value assignment
a = 33;
Combined declaration and assignment
int a = 33;

Lecture notes

  • Statements

Create comment

Expression vs. statement

Expression
++a - 4
Statement
b = ++a - 4;

Notice the trailing ;.

Lecture notes

  • Statements

Create comment

Multiple statements per line

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

Discouraged by good coding practices:

  • Poor readability

  • Hampers debugging

Lecture notes

  • Statements

Create comment

Debugging multiple statements per line

Debugging multiple statements per line

Lecture notes

  • Statements

Create comment

Blocks

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.

Lecture notes

  • Statements

Create comment

Overview

  • Statements
    • ➟ The if conditional statement

      Lecture notes

if block execution selection

double initialAmount = 320000.00;

if (100000 <= initialAmount) {
  // Rich customer, 1,2% interest rate
  System.out.println(
    "Interest:" + 1.2 * initialAmount / 100);
}
System.out.println("Done!");
Interest:3840.0
Done!
if block execution selection

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

if execution syntax

if (booleanExpression)
  (block | statement)

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

if ... else block execution selection

double initialAmount = 420.00;
...
if (100000 <= initialAmount )  { 
  // Rich customer, 1,2% interest rate
  System.out.println(
     "Interest:" + 1.2 * initialAmount / 100);
}  else { 
  // Joe customer, 0.8% standard interest rate
  System.out.println(
    "Interest:" + 0.8 * initialAmount / 100);
}
System.out.println("Done!");
Interest:3.36
Done!
if ... else block execution selection

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

if ... else execution syntax

if (booleanExpression)
   (block | statement)
[else
   (block | statement) ] 

The [...] pair of braces denotes an optional clause that may or may not be present.

Thus only the first part if (booleanExpression) (block | statement) is mandatory.

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Best practices comparing for equality

Always use

if (4 == variable) ...

in favour of:

if (variable == 4) ...

See detailed explanation.

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Followup exercises

Single statement branches

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);

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

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Aside: Corporate network security

Would you access your online bank account using Stuttgart Media University's network?

  1. Yes

  2. Only on private equipment (Smartphone, tablet, laptop, ...)

  3. Never!

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Online banking

Online banking

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

IP Spoofing

IP Spoofing

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Turn DNS name into IP address

~> nslookup 
> server 141.62.1.5 
Address: 141.62.1.5#53
> 
> meine.deutsche-bank.de 
Server:    141.62.1.5
Address:   141.62.1.5#53

Non-authoritative answer:
Name:   meine.deutsche-bank.de
Address: 129.35.230.2 

Entering DNS name.

IP address of meine.deutsche-bank.de is 129.35.230.2.

Caution: This IP value may become subject to tampering.

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

SSL Certificate error

SSL Certificate error

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

The Apple goto fail SSL bug

static OSStatus SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa,
       SSLBuffer signedParams, uint8_t *signature, UInt16 signatureLen) {
  OSStatus        err;
  ...
  if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
    goto fail;
  if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
    goto fail;
    goto fail;
  if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
    goto fail;

  err = sslRawVerify(...);
  ...
fail:
  SSLFreeBuffer(&signedHashes);
  SSLFreeBuffer(&hashCtx);
  return err;                   }

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Static code analysis

if ((err = SSLHashSHA1.update(...)) != 0)
  goto fail;
  goto fail;
Reachable code, err yet 0
if ((err = SSLHashSHA1.final(...)) != 0)
  goto fail;

err = sslRawVerify(...);  ...
Unreachable code
fail:
  SSLFreeBuffer(&signedHashes);
  SSLFreeBuffer(&hashCtx);
  return err;
Reachable code, err possibly still 0

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Followup exercise

No. 56: Static code analysis

Nested if ... else

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

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

if ... else if ... else

if ('A' == grade || 'B' == grade) {
   result = "Excellent";
} else if ('C' == grade) {
   result = "O.k.";
} else if ('D' == grade) {
   result = "Passed";
} else {
   result = "Failed";
}
if ... else if ... else

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

if ... else if ... else syntax

if (booleanExpression)
   (block | statement)
[else if (booleanExpression)
   (block | statement) ]* 
[else
  (block | statement) ] 

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

User input recipe

import java.util.Scanner;
public class App {
  public static void main(String[] args){

    try (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.

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Followup exercises

Converting numbers to day's names

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

1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Implementing number to day's names

try (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);
  }
}

Lecture notes

  • Statements
    • ➟ The if conditional statement

Create comment

Overview

  • Statements
    • ➟ The switch statement

      Lecture notes

Better: Using switch

...
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

Lecture notes

  • Statements
    • ➟ The switch statement

Create comment

switch Syntax

switch(expression) {
[case value_1 :
    [statement]*
    [break;] ]
[case value_2 :
    [statement]*
    [break;] ]
  ...
[case value_n :
    [statement]*
    [break;] ]
[default:
    [statement]*
    [break;] ]
}

Lecture notes

  • Statements
    • ➟ The switch statement

Create comment

Followup exercises

Switching on strings

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;
    }
}

Lecture notes

  • Statements
    • ➟ The switch statement

Create comment

Followup exercises

Overview

  • Statements
    • ➟ Loops

      Lecture notes

Why 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.

Lecture notes

  • Statements
    • ➟ Loops

Create comment

Arbitrary number of repetitions

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.

Lecture notes

  • Statements
    • ➟ Loops

Create comment

Overview

  • Statements
    • ➟ Loops
      • ➟ while

        Lecture notes

A while loop

final int repetitions = scan.nextInt(); 
int loopCount = 1; 

while (loopCount <= repetitions ) {
   System.out.println("Do not copy!"); 
   loopCount++; 
}
Do not copy!
Do not copy!
Do not copy!
A while loop

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ while

Create comment

Combining increment and termination condition

System.out.print("Enter repetitions: ");
final int repetitions = scan.nextInt();
int loopCounter = 1;

while (loopCounter++ <= repetitions) {
   System.out.println("Do not copy!");
}
Enter repetitions: 3
Do not copy!
Do not copy!
Do not copy!

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ while

Create comment

while syntax

while (booleanExpression)
   (block | statement)

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ while

Create comment

Empty while body

int threeSeries = 1;

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

System.out.println(threeSeries);

Exercise: Guess resulting output.

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ while

Create comment

A do ... while loop

int sum = 0, value;
do {
  System.out.print(
    "Enter value, 0 to terminate: ");
  value = scanner.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

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ do ... while

Create comment

do ... while syntax

do
  (block | statement)
while (booleanExpression);

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ do ... while

Create comment

Followup exercise

No. 66: Even or odd?

Overview

  • Statements
    • ➟ Loops
      • ➟ for

        Lecture notes

Frequent usage of while

int i = 1; 

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

Declaring and initializing a loop termination variable.

Check for loop termination.

Loop progression control

More concise syntax?

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for

Create comment

Replacing while by for

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

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

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for

Create comment

for syntax

for ( init ; booleanExpression ; update )
  (block | statement)

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for

Create comment

for variable scope

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

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for

Create comment

for variable scope equivalence

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

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for

Create comment

for vs. while relationship

while ( expression )
  (block | statement)
for ( ;expression ;)
  (block | statement)

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

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for

Create comment

Followup exercise

No. 67: Printing even numbers

Nested loops

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

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for

Create comment

Using row and column in favour of i and j

// 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();
}

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for

Create comment

Followup exercises

Overview

  • Statements
    • ➟ Loops
      • ➟ for
        • ➟ Loops and calculations

          Lecture notes

Calculating values

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

Lecture notes

  • Statements
    • ➟ Loops
      • ➟ for
        • ➟ Loops and calculations

Create comment

Followup exercises