if-then-else

Figure 144. if ... else Slide presentation
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

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 145. if ... else syntax Slide presentation
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 146. Best practices comparing for equality Slide presentation

Use

if (4 == variable) ...

in favour of:

if (variable == 4) ... 

Some programming languages allow for interpreting integer values as logical expressions. In »C / C++« for example an int value of zero is equivalent to false and nonzero values evaluate to true. Consider the following snippet:

if (variable = 4) {...} /* Just a single "=" rather then "==" */

A Java compiler will flag this as a compile time error. On contrary in »C / C++« this is perfectly correct code: The term variable = 4 having a nonzero value of 4 evaluates to true which in real code would most likely be a bug. Subject to choosing compiler warning options the possible damage may be mitigated depending on the observer's degree of pedantry.

Changing the order however even in »C / C++« results in a compile time error since we cannot assign a value to a literal:

if (4 = variable) {...} // Compile time error in C/C++ as well

We are thus able to avoid this type of error in the first place.


exercise No. 50

Providing better display

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 a negative value 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. You may reconsider the findings from Why using braces in System.out.println(...) ? .

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:

System.out.println(a + b + "=" + (a + b));
                    ╲  ╱    ╱      ╲ ╱ 
                     96    ╱        96
                       ╲  ╱        ╱ 
                       "96="      ╱ 
                          ╲      ╱ 
                           "96=96"

Resolving this issue may be effected by adding an empty string ❶ forcing Java to use the concatenation + operator in favour of the arithmetic one:

System.out.println(a + ""❶ + b + "=" + (a + b));
                    ╲ ╱       ╱            ╲ ╱ 
                   "100"     ╱             96
                      ╲     ╱             ╱ 
                       "100-4"           ╱ 
                             ╲          ╱ 
                              "100-4=96"
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. 51

Comparing for equality

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 count = 4 expression.

Tip

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

A:

The two operators = and == are completely unrelated:

=

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.

In particular an expression like count == 4 is of type boolean being either true or false.

More formally the expression count = 4 is of type int evaluating to 4 (surprise!). However an if (...) operates on boolean values only and if (4) thus does not make sense at all. The code in question may therefore 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 actually 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 due to operator priority rules:

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

Figure 147. Single statement branches Slide presentation

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

Figure 148. Nested if ... else Slide presentation
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