The if conditional statement

Figure 159. if block execution selection Slide presentation Create comment in forum
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

Figure 160. if execution syntax Slide presentation Create comment in forum
if (booleanExpression)
  (block | statement)

Figure 161. if ... else block execution selection Slide presentation Create comment in forum
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

Decision on boolean expression.

Conditional execution of on block or single statement.

Required branch being executed in case of boolean expression being true.

Optional branch corresponding to boolean expression being false.


Figure 162. if ... else execution syntax Slide presentation Create comment in forum
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.


Figure 163. Best practices comparing for equality Slide presentation Create comment in forum

Always use

if (4 == variable) ...

in favour of:

if (variable == 4) ...

See detailed explanation.


exercise No. 51

Providing better display Create comment in forum

Q:

We reconsider Working with variables :

Source code Output
int a = -4,
    b = 100;

System.out.println(a + "+" + b+ "=" + (a + b));
-4+100=96

Unfortunately changing the two variables' values yields:

Source code Output
int a = 100,
    b = -4;

System.out.println(a + "+" + b + "=" + (a + b));
100+-4=96

This result looks awkward. Modify the code to see 100-4=96 in such cases.

A:

The following simple solution does not work:

Source code Output
int a = 100,
    b = -4;

if (b < 0) {
    System.out.println(a + b + "=" + (a + b));
  } else {
    System.out.println(a + "+" + b + "=" + (a + b));
}
96=96

Since a and b are both variables of type int they get added rather than string style concatenated. Resolving this issue may be effected by adding an empty string ❶ forcing Java to use the concatenation + operator in favour of the arithmetic one:

Source code Output
int a = 100,
    b = -4;

if (b < 0) {
    System.out.println(a + "" ❶ + b+ "=" + (a + b));
  } else {
    System.out.println(a + "+" + b + "=" + (a + b));
}
100-4=96

exercise No. 52

Comparing for equality Create comment in forum

Q:

Copy the following snippet into your IDE:

int count = 1;

if (count = 4) { // is count equal to 4?
  System.out.println("count is o.K.");
}

The Java compiler will indicate an error:

Incompatible types.
Required: boolean
Found: int

Explain its cause in detail by examining the underlying expression.

Tip

Java provides two similar looking operators = and == having (totally) different semantics.

A:

Java provides two seemingly similar but completely unrelated operators:

=

This is being called the assignment operator. A typical statement reads a = 34 assigning the int value 44 to a variable a.

Note this operator's semantics being completely different from even elementary math syntax. Consider:

x = y x 2 = y 2

In math = denotes the equality of objects e.g. values, sets, functions and so on.

==

The comparison operator matching the usual math semantics comparing:

  • Java primitive types for equality of value.

  • Java objects for identity.

Thus (count = 4) is an expression evaluating to 4. So the code in question may be re-written as:

int count = 1;

int countAssignment = (count = 4); // Assigning expression count = 4 to variable countAssignment

if (countAssignment) { // Error: An int is not a boolean!
  System.out.println("count is o.K.");
}

This code is equivalent to its counterpart with respect to execution. The comment is count equal to 4? is thus misleading: The intended comparison requires using the == operator rather than an assignment operator =. Changing it the resulting expression is indeed of type boolean:

int count = 4 + 3;
final boolean test = (count == 4); // Now using "==" (comparison) in favour of "=" (assignment)
System.out.println("test=" + test);

This way our result reads test=false as expected. Thus our initial code just needs a simple modification:

int count = 1;

if (count == 4) { // is count equal to 4?
  System.out.println("count is o.K.");
}

Note

In contrast to Java some programming languages like C and C++ allow for integer values in if (...) conditionals:

#include <stdio.h>

int main(int argc, char **args) {

  int a = 3;
  if (a = 4) {
     printf("a has got a value of 4\n");
  }
}

The integer expression count = 4 has got a value of 4. Integer values inside an if (...) statement will be evaluated as:

true

if the expression's value differs from zero

false

if the expression's value equals zero

Thus in C and C++ the expression if(count = 4) will always evaluate to true irrespective of the variable count's initial value. Most important: The C compiler will not issue an error or warning unless non-default, more restrictive compile time warning options are being activated. Consider this widely used »feature« to be dangerous at best.

For this reason it is good practice always using if (4 == count) rather than if (count == 4): Even in C you cannot assign a value to a constant literal. Thus an accidentally mistyped if (4 = count) statement will definitively result in a compile time error most likely saving its author from tedious debugging.

exercise No. 53

Replacing else if (...){...} by nested if ... else statements Create comment in forum

Q:

A computer newbie did not yet read about the else if(...) branch construct but nevertheless tries to implement the following logic:

if (a < 7) {
  System.out.println("o.K.");
} else if (b == 5) {
  System.out.println("Maybe");
} else {
  System.out.println("Wrong!");
}

a and b are supposed to be int variables. Please help our newbie using just if(...){...} else {...} avoiding else if(...) {} branch statements!

Tip

As the title suggests you may want to nest an inner if(...) inside an outer one.

A:

The solution requires replacing the else if(...) branch by a nested if(...){ ...} else statement and moving the final else block into the nested one.

if (a < 7) {
    System.out.println("o.K.");
} else {
    if (b == 5) {
        System.out.println("Maybe");
    } else {
        System.out.println("Wrong!");
    }
}
Figure 164. Single statement branches Slide presentation Create comment in forum
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.


Figure 165. Aside: Corporate network security Slide presentation Create comment in forum

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

  • Yes

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

  • Never!


Figure 166. Online banking Slide presentation Create comment in forum
Online banking

Figure 167. IP Spoofing Slide presentation Create comment in forum
IP Spoofing

Figure 168. Turn DNS name into IP address Slide presentation Create comment in forum
~> nslookup 
> server 141.62.1.5 
Default 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 

Choosing a name server to query DNS names.

Entering DNS name.

Result: meine.deutsche-bank.de has got IP address 129.35.230.2.

Caution: This IP value may become subject to tampering.


Figure 169. SSL Certificate error Slide presentation Create comment in forum
SSL Certificate error

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

Figure 171. Static code analysis Slide presentation Create comment in forum
...
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

exercise No. 54

Static code analysis Create comment in forum

Q:

Consider the following snippet:

int count = 3;
count++;

if (count < 5)
    return;
    return;

System.out.println("Failed!");

This Java code mimics the Apple goto fail SSL bug's structural problem. Since Java does not offer goto statements we use return instead for terminating the current context.

Copy this code into your IDE and:

  1. Explain the resulting error. What is wrong? How do you correct this error?

  2. Explain the count++ statement's purpose.

    Tip

    There is no real application logic in the given code. It is an example meant to explain formal Java language features. What happens if you correct the compile time error and in addition purge the count++ statement?

  3. What is the underlying idea of these warning and error messages?

A:

  1. Like in the Apple goto fail SSL bug the code is poorly indented. Using your IDE's auto formatting feature (how?) you get:

    int count = 3;
    count++;
    
    if (count < 5)
        return;
    return;
    
    System.out.println("Failed!");

    The second return statement will leave the context unconditionally regardless of the preceding if (count < 5) and the count variable's value in particular. Thus the final System.out.println("Failed!") can never be reached resulting in a compile time error.

    Removing the erroneous return resolves the error leaving us with happily compiling code:

    int count = 3;
    count++;
    
    if (count < 5)
        return;
    
    System.out.println("Failed!");

    Conclusion: The Apple goto fail SSL bug could not have been occurring in Java due to language features.

  2. Removing count++ leaves us with:

    int count = 3;
    
    if (count < 5) 
        return;
    
    System.out.println("Failed!");

    Compiler warning: Condition 'count < 5' is always 'true'.

    This warning is due to static compile time code analysis: The count variable's value is not being altered throughout its scope. It could actually be declared as final int count = 3 disallowing subsequent assignments. Thus the return inside if (count < 5) will always be executed.

    Despite its simplicity having the count++ statement in place defeats the compiler's ability to discover that count now having a value of 4 still being smaller than 5.

  3. The underlying idea is preventing programmers from coding carelessly: Even the if (count < 5) statement is most likely an unintended bug.

Important

Conclusion: Watch out for compiler warning messages and do not ignore them!

In many cases compiler warnings reveal serious flaws. Correction on average will save you lots of cumbersome time debugging your code.

Figure 172. Nested if ... else Slide presentation Create comment in forum
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

Figure 173. if ... else if ... else Slide presentation Create comment in forum
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

Figure 174. if ... else if ... else syntax Slide presentation Create comment in forum
if (booleanExpression)
   (block | statement)
[else if (booleanExpression)
   (block | statement) ]* 
[else
  (block | statement) ] 

The pair of braces [...] indicates an optional clause. The asterisk * indicates an arbitrary number of repetitions (zero to infinity).

The second pair of braces [...] again indicates an optional clause.

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


Figure 175. User input recipe Slide presentation Create comment in forum
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:1234567
You entered 1234567

See nextBoolean(), nextByte() and friends.


exercise No. 55

Post modifying an exam's marking Create comment in forum

Q:

After completely marking an examination a lecturer decides to globally add a number extra bonus points to a specific task . The task does have an upper limit of points to be awarded at maximum. We provide an example:

On completely fulfilling a given task 12 points will be awarded. So after marking the exam participants' points range from 0 to 12 points being represented by the variable pointsReached.

After completing his marking our lecturer wants to add three more points to all participants without breaching the 12 point limit.

Complete the following code by assigning this modified number of points to the variable newResult.

public static void main(String[] args) {

  int pointsReached = 1;
  int maximumPoints = 12;
  int pointsToAdd = 3;

  final int newResult;

  // TODO: Assignment to variable newResult

  System.out.println("New Result:" + newResult);
}

A:

The basic task is to add up the values of pointsReached and pointsToAdd. When exceeding the limit we just assign the limit itself:

public static void main(String[] args) {

  final int pointsReached = 1;
  final int maximumPoints = 12;
  final int pointsToAdd = 3;

  final int newResult;

  if (maximumPoints <= pointsReached + pointsToAdd) {
    newResult = maximumPoints;
  } else {
    newResult = pointsReached + pointsToAdd;
  }

  System.out.println("New Result:" + newResult);
}

This basically means calculating the minimum of the two expressions pointsReached + pointsToAdd and maximumPoints. This may as well be be implemented by:

public static void main(String[] args) {

  final int pointsReached = 1;
  final int maximumPoints = 12;
  final int pointsToAdd = 3;

  final int newResult = Math.min(maximumPoints, pointsReached + pointsToAdd);

  System.out.println("New Result:" + newResult);
}

You will fully understand the above expression Math.min(...) after finishing the Static Final Variables section of [Kurniawan].

exercise No. 56

At the bar Create comment in forum

Q:

This example uses existing program code to be explained later. You'll implement an interactive application which implements a dialogue with a user asking for input to be entered in a terminal like window as being shown in the following video:

Figure 176. Using a Scanner class collecting user input. Slide presentation Create comment in forum

A bar uses a software system for picking up orders. The bar will serve just orange juice and beer. For legal reasons the latter will only be served to persons of at least 16 years of age. We show three possible user dialogues:

  1. On offer:
      1=Beer
      2=Orange juice
    
    Your choice:>1
    Tell me your age please:>15
    Sorry, we are not allowed to serve beer to underage customers
  2. On offer:
      1=Beer
      2=Orange juice
    
    Your choice:>2
    o.K.
  3. On offer:
      1=Beer
      2=Orange juice
    
    Your choice:>4
    Sorry, invalid choice

Since you may not yet know how to enable Java applications asking for user input simply use the following recipe to get started:

public static void main(String[] args) {

  try (final Scanner scan = new Scanner(System.in)) { // Creating a scanner for reading user input

    System.out.print("Please enter a value:");
    final int userInput = scan.nextInt();

    System.out.println("You entered: " + userInput);
    // TODO: Implement »at the bar« logic

  } // Auto closing scanner
}

Copy this boilerplate code into your IDE. The IDE will assist you adding a required import java.util.Scanner; statement in your code's header section. Execute this code. You should see a dialogue like:

Please enter a value:112
You entered: 112

Then extend the above code implementing the desired behaviour.

A:

package start;

import java.util.Scanner;

public class BarOrder {

    public static void main(String[] args) {

        final Scanner scan = new Scanner(System.in);
        System.out.print("On offer:\n  1=Beer\n  2=Orange juice\n\nYour choice:>" );

        final int beverageChoice = scan.nextInt(); // Read user input

        switch (beverageChoice) {
            case 1:
                System.out.print("Tell me your age please:>");
                final int age = scan.nextInt();
                if (age < 16) {
                    System.out.println("Sorry, we are not allowed to serve beer to underage customers");
                } else {
                    System.out.println("o.K.");
                }
                break;

            case 2:
                System.out.println("o.K.");
                break;

            default:
                System.err.println("Sorry, invalid choice");
                break;
        }
        scan.close();
    }
}

exercise No. 57

Roman numerals Create comment in forum

Q:

Write an application which turns a positive integer values up to and including 10 into Roman numeral representation:

Enter a number:>9
IX

Regarding user input you may start from ??? again. If the user enters a value smaller than one or greater than ten the following output is to be expected:

Enter a number:>11
Decimal value 11 not yet implemented

Tip

You may use a series of if () {...} else if () {...} ... statements.

A:

try (final Scanner scan = new Scanner(System.in)) {

  System.out.print("Enter a number:>");
   final int number = scan.nextInt();

   if (1 == number) {
      System.out.println("I");
   } else if (2 == number) {
      System.out.println("II");
   } else if (3 == number) {
       System.out.println("III");
   } else if (4 == number) {
       System.out.println("IV");
   } else if (5 == number) {
       System.out.println("V");
   } else if (6 == number) {
       System.out.println("VI");
   } else if (7 == number) {
       System.out.println("VII");
   } else if (8 == number) {
       System.out.println("VIII");
   } else if (9 == number) {
       System.out.println("IX");
   } else if (10 == number) {
       System.out.println("X");
   } else {
       System.out.println("Decimal value " + number + " not yet implemented");
   }
}
Figure 177. Converting numbers to day's names Slide presentation Create comment in forum

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

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

Figure 178. Implementing number to day's names Slide presentation Create comment in forum
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);
  }
}