Operators and expressions
No. 35
int
to short
assignment
Q: 
Consider the following code segment:
On contrary the following line will compile flawlessly: Figure 148. Constant expression assignment
short sum = 4 + 7; Explain this strange behaviour. 

A: 
Considering The expression 
No. 36
int
to short
assignment using final
Q: 
We reconsider a variant of Figure 147, “ 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 148, “Constant expression assignment” code sample the
resulting value of 
No. 37
Dividing values
Q: 
Consider the following statement: System.out.println(8 / 9); The output is 
A: 
The divide operator acts on two 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 
No. 41
Expressions involving infinity
Q: 
Figure 150, “Dividing by zero ” raises some interesting questions:

A: 

Left  Right  Out  Examples 

boolean 
boolean 
boolean 
, &, &&, , ^ 
int 
int 
int 
+, , *, /, % (read here!) 
int 
long 
long 

byte 
short 
int 

double 
float 
double 

int 
float 
float 

char 
byte 
int 
The careful reader may
stumble upon the absence of e.g. a «+» operator turning two byte values
a
and b
into an
expression a + b
of type byte
rather than int
.
This is due to a Java Virtual Machine design
decision leading to a limited
set of computational types:
Given the Java Virtual Machine's onebyte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine's runtime data types, there would be more instructions than could be represented in a byte. Instead, the instruction set of the Java Virtual Machine provides a reduced level of type support for certain operations. In other words, the instruction set is intentionally not orthogonal. Separate instructions can be used to convert between unsupported and supported data types as necessary.
No. 42
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 to standard output */); } TipYou may want to read the overview section on statements in [Kurniawan]. 
A: 

No. 43
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. 44
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. 45
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. 46
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. 47
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. 48
Time unit conversion
Q: 
This is a two part exercise:

A: 

No. 49
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. 50
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 
//Integer i++; i = i + 1; // Increment by one i; i = i  1; // Decrement by one i += b; i = i + b; // Raise by b's value i %= 3; i = i % 3; // Modulus of 3 // boolean b = !b; // Switching true <> false
No. 51
Guessing results
Q: 
Consider the following code segment: int a = 3;
a++; // Incrementing a by 1 > a==4
int b = a; // TODO
b; // TODO
b; // TODO
int c = b; // TODO
b = ++a; // TODO
int e = a++; // TODO
a *= b; // TODO
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("c=" + c);
System.out.println("e=" + e); We want to guess the expected result. Copy/paste the above code into a main() method body within your IDE of choice. Do not execute this code yet but replace the “TODO” strings by guessing the respective variable's value beforehand as in line 2:
After finishing your guesses execute your code and (possibly) start wailing about your success rate. TipBoth 
A: 
As inferred by the hint the biggest problem is about
understanding postfix and infix notation of the operators
The rest is just obeying the “due diligence” rule set: int a = 3;
a++; //Incrementing a by 1 > a==4
int b = a; // Assigning value of a > b==4
b; // Decrementing b by 1 > b==3
b; // Decrementing b by 1 > b==2
int c = b; // c == 2;
b = ++a; // Incrementing a by 1 >a==5, then assigning to b > b == 5
int e = a++; // Assigning a to e > e==5, then incrementing a > a==6
a *= b; // Multiplying a with b and assigning the result to a > a==30
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("c=" + c);
System.out.println("e=" + e); 
No. 52
Cleaning up the mess
Q: 
Some developers follow the rule “It was hard to write, it should be hard to understand as well”. One such proponent codes: int a = 3, b = 6, c = 2; a += (a = 2) + ++a  ++b % c; System.out.println("a = " + a + ", b = " + b + ", c = " + c); Execution results in: a = 7, b = 7, c = 1 Decompose this cryptic assignment into a series of multiple
elementary ones like e.g. TipRead about evaluation of expressions and operator precedence. 
A: 
We start by modifying the line in question: a = a + (a = 2) + ++a  ++b % c; The expression on the right hand side will be decomposed by the Java™ compiler into a sum of four subexpressions to be evaluated from left to right:
We introduce a helper variable int a = 3, b = 6, c = 2; int sum = a; // First subexpression a = 2; sum += a; // Second subexpression a++; sum += a; // Third subexpression b++; sum = b % c; // Fourth subexpression c; a = sum; // Assigning the result System.out.println("a = " + a + ", b = " + b + ", c = " + c); 