From blocks to methods

Figure 161. Two blocks, same logic Slide presentation
final int agePeter = 26,
          ageCarmen = 30;

final int maxAge;
{
   if (agePeter > ageCarmen) {     
      maxAge = agePeter;
   } else {
      maxAge = ageCarmen;
   }
}
...
...
final int heightDenali = 6910,
          heightCerroTorre = 3128;

final int maxHeight;
{ // Exact same logic as before
   if (heightDenali > heightCerroTorre) {     
      maxHeight = heightDenali;
   } else {
      maxHeight = heightCerroTorre;
   }
}

Figure 162. Replace blocks by method Slide presentation
void main() {
    final int agePeter = 26, ageCarmen = 30;
    final int maxAge = max(agePeter, ageCarmen);

    final int heightDenali = 6910, heightCerroTorre = 3128;
    final int maxHeight = max(heightDenali, heightCerroTorre);
}

int max (int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}

exercise No. 61

Computing the absolute value

Q:

Implement a method int abs(int value){...} to compute an expression's absolute value to be used like e.g.:

Code
IO.println(abs(-10));
IO.println(abs(8)); 
Result
10
8

A:

int abs (int value) {
    if (value > 0) {
        return value;
    } else {
        return -value;
    }
}

exercise No. 62

Absolute value, flawed implementation

Q:

We consider an alternate solution of Computing the absolute value :

int abs (int value) {
    if (value > 0) {
        return value;
    } else if (value < 0){
        return -value;
    }
}

This yields a compile time Missing return statement error. What's wrong here? Provide a solution differing from Computing the absolute value .

A:

The abs(int value) {...} must return a value for arbitrary values. This is not the case for value == 0. But even the following code is prone to the very same error message:

int abs (int value) {
    if (value > 0) {
        return value;
    } else if (value < 0){
        return -value;
    } else if( value == 0) {
        return 0;
    }
}

Reason: A Java compiler is simply not clever enough to realize, that indeed all possible values are being handled here. We require an unconditional else {...} clause:

int abs (int value) {
    if (value > 0) {
        return value;
    } else if (value < 0){
        return -value;
    } else { // value == 0
        return 0;
    }
}

This is actually a minor regression in comparison to Computing the absolute value : In case of value == 0 we now require two comparisons rather than one.