Arithmetic and logical operators
No. 28
Calculating a circle's area
Q: |
The area
of a given circle having radius
is being obtained by
. Complete the following code to calculate
the result and write it to standard output using
TipYou may want to read the overview section on statements in [Kurniawan]. |
A: |
|
No. 29
Dividing values
Q: |
Consider the following statement:
The output is |
A: |
The divide operator acts on two literals 8 an 9 of type
According to |
No. 30
Strange things with operator ++
Q: |
TipYou may want to read the overview section on statements in [Kurniawan]. |
||||||
A: |
Conclusion: |
No. 31
Adding values
Q: |
Consider the following code:
This yields: -2147483648 2147483648 Explain this result. Please refrain from answering “Thats what bankers do!” |
A: |
The value 2147483647 is actually the largest possible
On binary level adding an 01111111_11111111_11111111_11111111 2147483647 + 00000000_00000000_00000000_00000001 + 1 ------------------------------------- ------------ 10000000_00000000_00000000_00000000 -2147483648 With respect to two-complement representation of signed
On contrary the plus operator in the expression 01111111_11111111_11111111_11111111 2147483647 + 00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001 + 1 ------------------------------------------------------------------------- ------------ 00000000_00000000_00000000_00000000_10000000_00000000_00000000_00000000 2147483648 Due to a |
No. 32
Representational float and double miracles
Q: |
Consider and execute the following code snippet:
Which outcome do you expect? Explain the execution's result and propose a solution. Tip
|
||||
A: |
The expression Adding Comparing
The last line represents the boolean expression . So two values will be regarded as equal if their mutual distance is less than 0.00000000000001. |
try {
int sum = Math.addExact(2147480000, 2147480000);
System.out.println("sum = " + sum);
} catch (ArithmeticException ex) {
System.err.println("Problem: " + ex.getMessage());
}
Problem: integer overflow
|
Value: Infinity |
Watch out: “Silent” error!
No. 33
Expressions involving infinity
Q: |
Figure 116, “Dividing by zero ” raises some interesting questions:
|
A: |
|
Get a division's remainder:
int nuggets = 11,
diggers = 3;
System.out.println("Nuggets per digger:" + nuggets / diggers);
System.out.println("Remaining nuggets:" + nuggets % diggers); |
Nuggets per digger:3 Remaining nuggets:2 |
Left | Right | Out | Examples |
---|---|---|---|
boolean |
boolean |
boolean |
|, &, &&, ||, ^ |
int |
int |
int |
+, -, *, /, % (read here!) |
int |
long |
long |
|
byte |
byte |
int |
|
double |
float |
double |
|
int |
float |
float |
|
char |
byte |
int |
The careful reader may
stumble upon the absence of e.g. a binary «+» operator turning two byte
values a
and b
into an expression a + b
of type byte
rather than int
:
byte a = 1, b = 2;
byte sum = a + b; // Error: Incompatible types. ❶
// Required: byte
// Found: int
This is due to a Java Virtual Machine design decision leading to a limited set of computational types:
|
No. 34
int
to short
assignment
Q: |
Consider the following code segment:
On contrary the following statement compiles flawlessly: Figure 122. Constant expression assignment
Explain this strange behaviour. |
||||
A: |
Considering The expression |
No. 35
int
to short
assignment using final
Q: |
We reconsider a variant of Figure 121, “ final short a = 4;
short sum = a + 7; This time the code compiles flawlessly. Explain the
underlying reason being related to the |
A: |
A final variable's value cannot change. Thus the
expression a + 7 is fully equivalent to 4 + 7 and can thus be
evaluated at compile time. Like in the
preceding Figure 122, “Constant expression assignment”
code sample the resulting value of |
No. 36
Calculating a circle's area avoiding accidental redefinition
Q: |
In Exercise Calculating a circle's area you calculated a given circle's area:
Though there is nothing wrong with this approach it is
error prone: A careless programmer might accidentally redefine
the value of
Modify the above code to avoid this type of error. Tip
|
||||
A: |
The solution is straightforward. We just add a final ❶ double pi = 3.141592653589793; ... pi = -4; ❷ ...
As a rule of thumb: Whenever you intend a variable not to
change after an initial assignment use In addition refactoring our variable
|
No. 37
Turning weeks into seconds
Q: |
Consider:
Create an expression based on the variables After you have completed this task read about Horner's rule and try to improve your solution with respect to execution time. |
A: |
A straightforward solution reads:
This requires four additions and 10 multiplications. Horner's rule allows for:
This still leaves us with four additions but just 4 instead of 10 multiplications. Within the given context the difference in execution time can be neglected. But in a larger application the calculation in question might have to be repeated millions of times giving rise to a substantial gain with respect to execution time. |
No. 38
Turning seconds into weeks
Q: |
This exercise is about reversing Turning weeks into seconds namely decomposing a given value of elapsed seconds into weeks, days, hours, minutes and seconds:
TipAs an example consider decomposing 192 seconds into minutes and seconds:
Thus 192 seconds equal 3 minutes and 12 seconds |
A: |
We extend the given minute calculation example to all 5 desired values:
|
No. 39
Using predefined Java™ standard library constants
Q: |
In the previous exercise we coded:
Do we actually have to provide the value of pi (3.141592653589793) ourself? TipConsider the standard Math library. |
A: |
The solution is straightforward using Math.PI:
|
No. 40
Converting temperature values
Q: |
Write an application converting temperature values being represented as degree centigrade to kelvin and Fahrenheit:
|
A: |
|
No. 41
Time unit conversion
Q: |
This is a two part exercise:
|
A: |
|
No. 42
Interest calculation
Q: |
We want to calculate the compounded interest starting from an initial capital, a given annual interest rate and a duration of three years. Consider the following code fragment:
The expected output is: Initial capital: 223.12€ Annual interest rate: 1.5% Interest period: 3 years Capital after three years:233.31175902999993 Extend the given code accordingly. TipIn case you are unsure read about calculating compounded interest. In case you already have prior knowledge about loop statements in Java™ you may want to allow for a variable number of years: // Interest parameters
final double initialCapital = 223.12;
final double interestRate = 1.5;
final int interestPeriodInYears = 3;
...
// Printing result
System.out.println("Capital after three years:" + finalCapital); |
A: |
We obtain the three year's compounded interest by: Since we have not yet introduced loops the multiplication has to be repeated three times ❶:
We might as well use a single arithmetic expression achieving the same result:
Using loop statements our solution becomes more flexible with respect to the interest period in question:
In the section called “Interest calculations” we will present an even more elaborate solution based on classes. |
No. 43
Summing short and char
Q: |
Consider the following snippet:
Execution results in TipTry to assign the expression to another variable and experiment using type candidates. Try to make an educated guess explaining the result. |
A: |
Both
According to the compiler's error message the expression
The two input types have different ranges:
A promotion to |
Boolean “and” of two operands:
boolean examSuccess = true,
registered = false;
boolean examPassed = examSuccess & registered;
System.out.println("Exam passed:" + examPassed); |
Exam passed:false |
No. 44
Operator & vs. &&
Q: |
Execute the following snippet:
Note the resulting output. Then replace the operator TipRead 15.22.2
and 15.23 to understand the difference between |
A: |
Execution yields: Exam success:false, points = 5 On modifying our code by Exam success:false, points = 4 The operators The The Likewise the |