From blocks to methods
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; } } |
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);
}
// Method replacing blocks
//
int max (int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
} No. 66
Computing the absolute value
|
Q: |
Implement a method
|
||||
|
A: |
|
No. 67
Absolute value, flawed implementation
|
Q: |
We consider an alternate solution of Computing the absolute 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
Reason: A Java compiler is simply not “clever”
enough to realize, that indeed all possible values are being
handled here. We require an unconditional This is actually a minor regression in comparison to Computing the absolute value : In case of |
No. 68
Arithmetic mean
|
Q: |
Implement a method computing the arithmetic mean of two values: Usage example:
|
||||
|
A: |
The following naïve approach does not work: Executing |
| Code | Result |
|---|---|
void main() {
int argument = 2;
int square = getSquare(argument);
IO.println("Square=" + square);
IO.println("Argument=" + argument);
}
/**
* Compute the square x * x of a value x.
*
* @param x Value
* @return Square of value.
*/
int getSquare(int x) {
x *= x;
return x;
} |
Square=4
Argument=??? |
void main() { int argument = 2; int square = getSquare(argument); IO.println("Square=" + square); IO.println("Argument=" + argument); } int getSquare(int x) { x *= x; return x; } |
int argument = 2; int square; { int x = argument; // argument unchanged x *= x; square = x; } IO.println("Square=" + square); IO.println("Argument=" + argument); |
Remark: This is a call-by-value method call.
No. 69
Analyzing a method call
|
Q: |
Analyze the call of main(...) to
|
|
A: |
The variables |
