if-then-else

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

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

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 34 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.");
}

Since the assignment operator is being evaluated from right to left we do not need braces:

...
int countAssignment = count = 4; // Assigning expression count = 4 to variable countAssignment
...

This code is equivalent to its counterpart with respect to compilation. 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);

Again we may omit braces here:

...
final boolean test = count == 4; // Now using "==" (comparison) in favour of "=" (assignment)
...

The boolean variable test will receive a value of false as expected. Thus our initial code just needs a tiny modification replacing the assignment operator «=» by the comparison operator «==»:

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

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 189. 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 190. Aside: Corporate network security Slide presentation Create comment in forum

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

  1. Yes

  2. Only on private equipment (Smart phone, tablet, laptop, ...)

  3. Never!


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

Figure 192. DNS Spoofing Slide presentation Create comment in forum
DNS Spoofing

Figure 193. Turn DNS name into IP address Slide presentation Create comment in forum
~> 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 

Nameserver answering DNS queries.

Entering DNS name.

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

Caution: This IP value may become subject to tampering.


Figure 194. 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 196. 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: Variable err unchanged.
fail:
  SSLFreeBuffer(&signedHashes);
  SSLFreeBuffer(&hashCtx);
  return err;
Reachable code, err possibly still 0

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