Operators and expressions
No. 34
Expressions and type
Q: 
Consider the following code segment: short a = 4; ❶ short sum = a + 7; ❷
On contrary the following line will compile flawlessly: short sum = 4 + 7; Explain this strange behaviour. 

A: 
The expression The very same argument seems to apply for the expression

No. 35
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. 36
Strange things happen
Q: 
TipYou may want to read the overview section on statements in [Kurniawan]. 

A: 

No. 37
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. 38
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. 39
Expressions involving infinity
Q: 
Figure 145, “Dividing by zero ” raises some interesting questions:

A: 

Left  Right  Out  Examples 

boolean 
boolean 
boolean 
, &, &&, , ^ 
int 
int 
int 
+, , *, /, % 
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. 40
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. 41
Calculating the area of a circle 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: In a similar program a careless programmer 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 we may refactor 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; radius = 1.8; System.out.println("A circle of radius " + radius + " will cover an area of " + PI * radius * radius); 
No. 42
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. We may use: ... final int secondsElapsed = seconds + 60 * (minutes + 60 * (hours + 24 * (days + 7 * weeks))); ... This 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 different application the calculation in question might have to be repeated millions of times giving rise to a substantial gain with respect to total execution time. 
No. 43
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. 44
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. 45
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. 46
Time unit conversion
Q: 
This exercise consists of two parts:

A: 

No. 47
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. 48
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 
i++; i = i + 1; i; i = i  1; i += b; i = i + b; i %= 3; i = i % 3; // boolean b = !b; // true <> false
No. 49
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. 50
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); 