Arithmetic and logical operators
No. 36
Calculating a circle's area
Q: 
The area
$a$ of a given circle having radius
$r$ is being obtained by
$a=\pi \times {r}^{2}$. Complete the following code to calculate
the result and write it to standard output using public static void main(String[] args) { double radius = 2.31; // A circle having a radius (given e.g. in mm). double pi = 3.1415926; // Constant relating a circle's radius, //perimeter and area. System.out.println( /* TODO: Write the circle's area in terms of both variables radius and pi */); } TipYou may want to read the overview section on statements in [Kurniawan]. 
A: 

No. 37
Dividing values
Q: 
Consider the following statement: System.out.println(8 / 9); The output is 
A: 
The divide operator acts on two literals 8 an 9 of type
According to 
No. 38
Strange things happen
Q: 
TipYou may want to read the overview section on statements in [Kurniawan]. 

A: 

No. 39
Adding values
Q: 
Consider the following code: System.out.println(2147483647 + 1); System.out.println(2147483647 + 1L); 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 twocomplement 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. 40
Representational float and double miracles
Q: 
Consider and execute the following code snippet: public static void main(String[] args) { final double a = 0.7; final double b = 0.9; final double x = a + 0.1; // 0.8 final double y = b  0.1; // 0.8 System.out.println(x == y); } Which outcome do you expect? Explain the execution's result and propose a solution. TipYou will have to replace the “==” operator by something more appropriate addressing limited arithmetic precision. 
A: 
The expression Adding Comparing final double a = 0.7; final double b = 0.9; final double x = a + 0.1; final double y = b  0.1; System.out.println(Math.abs(x  y) < 1.E14); The last line represents the boolean expression $\leftxy\right<{\mathrm{10}}^{\mathrm{14}}$. 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
double f = 34.3 / 0; System.out.println("Value: " + f); 
Value: Infinity 
Watch out: “Silent” error!
No. 41
Expressions involving infinity
Q: 
Figure 159, “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. 42
int
to short
assignment
Q: 
Consider the following code segment:
On contrary the following statement compiles flawlessly: Figure 165. Constant expression assignment
short sum = 4 + 7; Explain this strange behaviour. 

A: 
Considering The expression 
No. 43
int
to short
assignment using final
Q: 
We reconsider a variant of Figure 164, “ 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 165, “Constant expression assignment”
code sample the resulting value of 
No. 44
Calculating a circle's area avoiding accidental redefinition
Q: 
In Exercise Calculating a circle's area you calculated a given circle's area: public static void main(String[] args) { double radius = 2.31; // A circle having a radius (given e.g. in mm). double pi = 3.1415926; // Constant relating a circle's radius, perimeter //and area. double area = pi * radius * radius; System.out.println(area); } Though there is nothing wrong with this approach it is
error prone: A careless programmer might accidentally redefine
the value of double pi = 3.141592653589793; double radius = 2.3; // Computing a circle's area System.out.println("A circle of radius " + radius + " will cover an area of " + pi * radius * radius); pi = 4; // Woops, accidential redefinition radius = 1.8; System.out.println("A circle of radius " + radius + " will cover an area of " + pi * radius * radius); 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 final double PI = 3.141592653589793; double radius = 2.3; // Computing a circle's area System.out.println("A circle of radius " + radius + " will cover an area of " + PI * radius * radius); PI = 4; // Compile time error radius = 1.8; System.out.println("A circle of radius " + radius + " will cover an area of " + PI * radius * radius); 
No. 45
Turning weeks into seconds
Q: 
Consider: final short weeks = 2, days = 3, hours = 14, minutes = 32, seconds = 55; final int secondsElapsed = ...; // TODO: assign elapsed seconds corresponding to previous time frame. System.out.println(secondsElapsed); 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: final short weeks = 2, days = 3, hours = 14, minutes = 32, seconds = 55; final int secondsElapsed = seconds + 60 * minutes + 60 * 60 * hours + 60 * 60 * 24 * days + 60 * 60 * 24 * 7 * weeks; System.out.println(secondsElapsed); This requires four additions and 10 multiplications. Horner's rule allows for: ... final int secondsElapsed = seconds + 60 * (minutes + 60 * (hours + 24 * (days + 7 * weeks))); ... 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. 46
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: final int secondsElapsed = 1521175;
final int weeks = ...; // TODO
final int days = ...;// TODO
final int hours = ...;// TODO
final int minutes = ...;// TODO
final int seconds = ...;// TODO
System.out.println(weeks + ", " + days + ", " + hours + ", " + minutes + ", " + 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. For the sake of convenience the number of seconds per minute, per hour and so on are being calculated beforehand: final int secondsElapsed = 1521175; // Defining helpful constants // final int secondsPerMinute = 60, // 60 minutes per hour secondsPerHour = 60 * secondsPerMinute, // 3600 seconds per hour secondsPerDay = 24 * secondsPerHour, // 86400 seconds per day secondsPerWeek = 7 * secondsPerDay; // 604800 seconds per week int remainingSeconds = secondsElapsed; final int weeks = remainingSeconds / secondsPerWeek; remainingSeconds = remainingSeconds % secondsPerWeek; final int days = remainingSeconds / secondsPerDay; remainingSeconds %= secondsPerDay; final int hours = remainingSeconds / secondsPerHour; remainingSeconds %= secondsPerHour; final int minutes = remainingSeconds / secondsPerMinute; remainingSeconds %= secondsPerMinute; final int seconds = remainingSeconds; System.out.println(weeks + ", " + days + ", " + hours + ", " + minutes + ", " + seconds); 
No. 47
Using predefined Java™ standard library constants
Q: 
In the previous exercise we coded: final double PI = 3.141592653589793; double radius = 2.3; // Computing a circle's area System.out.println("A circle of radius " + radius + " will cover an area of " + PI * radius * radius); 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: double radius = 2.3; // Computing a circle's area
System.out.println("A circle of radius " + radius + " will cover an area of " +
Math.PI * radius * radius); 
No. 48
Converting temperature values
Q: 
Write an application converting temperature values being represented as degree centigrade to kelvin and Fahrenheit: public static void main(String[] args) {
double temperatureCelsius = 23.2;
...
System.out.println("Celsius: " + temperatureCelsius);
System.out.println("Kelvin: " + temperatureKelvin);
System.out.println("Fahrenheit: " + temperatureFahrenheit);
} 
A: 
public static void main(String[] args) { double temperatureCelsius = 23.2; double temperatureKelvin = temperatureCelsius + 273.15, temperatureFahrenheit = 9 * temperatureCelsius / 5 + 32; System.out.println("Celsius: " + temperatureCelsius); System.out.println("Kelvin: " + temperatureKelvin); System.out.println("Fahrenheit: " + temperatureFahrenheit); } 
No. 49
Time unit conversion
Q: 
This is a two part exercise:

A: 

No. 50
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: public static void main(String[] args) { final double initialCapital = 223.12; final double interestRate = 1.5; System.out.println("Initial capital:" + initialCapital); System.out.println("Annual interest rate:" + interestRate); // TODO ... System.out.println("Capital after three years:" + ...); } The expected output is: Initial capital:223.12 Annual interest rate:1.5 Capital after three years:233.31175902999993 TipIn case you are unsure read about calculating the compounded interest. 
A: 
We obtain the compounded interest by multiplying the initial capital by $1+r/100$ for each year where r represents the given interest rate. Since we have not yet introduced loops this multiplication has to be repeated three times: public static void main(String[] args) { final double initialCapital = 223.12; final double interestRate = 1.5; System.out.println("Initial capital:" + initialCapital); System.out.println("Annual interest rate:" + interestRate); final double factor = 1. + interestRate/100.; double capitalAtThreeYears = initialCapital; capitalAtThreeYears *= factor; // Year 1 capitalAtThreeYears *= factor; // Year 2 capitalAtThreeYears *= factor; // Year 3 System.out.println("Capital after three years:" + capitalAtThreeYears); } We might as well use a single arithmetic expression to achieve the same result: public static void main(String[] args) { final double initialCapital = 223.12; final double interestRate = 1.5; System.out.println("Initial capital:" + initialCapital); System.out.println("Annual interest rate:" + interestRate); final double factor = 1. + interestRate/100.; final double capitalAtThreeYears = initialCapital * factor * factor * factor; System.out.println("Capital after three years:" + capitalAtThreeYears); } In the section called “Interest calculations” we will present a more elaborate solution based on loops and class methods. 
No. 51
Summing short and char
Q: 
Consider the following snippet: short s = 1;
char c = 'A'; // ASCII 65
System.out.println(s + c); 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 short s = 1;
char c = 'A';
short resultShort = s + c; // Incompatible types Required: short found: int
char resultChar= s + c; // Incompatible types Required: char found: int 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. 52
Operator & vs. &&
Q: 
Execute the following snippet: int points = 4; boolean registered = false; boolean examSuccess = registered & 4 <= points++; System.out.println("Exam success:" + examSuccess + ", points = " + points); 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 