Conversions
byte b = 42; // Narrowing: constant int literal to byte
short s = b; // Widening
int i = s; // Widening
long l = i; // Widening
float f = l; // Widening
double d = f; // Widening
double d = 14.23;
float f = (float) d; // Narrowing
long l = (long) f; // Narrowing
int i = (int) l; // Narrowing
short s = (short) i; // Narrowing
byte b = (byte) s; // Narrowing
No. 27
int
and char
Q: |
Explain the following output:
Why do we see a result of 65535 rather than -1? TipRead about the a |
||||||||||||||||
A: |
In contrast to
Like with other integer types the above table behaves in a cyclic way with respect to additions at its top and and subtractions at its bottom:
On machine level this may be conceived as an (incomplete) subtract operation: 0000 0000 0000 0000 -0000 0000 0000 0001 -------------------- 1111 1111 1111 1111 |
No. 28
float
vs. double
Q: |
We consider:
There seems to be no difference between the three literals
TipRead the section about floating point literals in Java™. Write code exhibiting possible differences. Use e.g. System.out.format("%.16f\n", floatOrDoubleValue); for printing values with 16 digits precision. |
||||||||||||||||||||||||||||||||
A: |
The System.out.println( 3.14f ) statement's output is actually truncated with respect to output precision. Forcing 16 fractional digits to become visible reads:
The value 3.1400001049041750 is the closest
possible approximation to 3.14 when using a 4-byte IEEE
float. A
This difference is a result of Regarding types we have:
Assignments to variables of type
Assignments to variables of type
|
No. 29
int
to char
narrowing
problems
Q: |
Reconsidering Figure 107, “Narrowing from
Explain these errors and their underlying reasons and provide a solution if possible. TipWhich data types are involved? Think about narrowing conversions and type casting. |
A: |
|
No. 30
Get a byte
from 139
Q: |
Consider:
Explain in detail why execution results in a value of
|
A: |
No. 31
Ariane, I miss you!
Q: |
Reconsidering the Ariane 5 maiden flight
crash read the comment buried in the solution of Inventing Start with a Then in a second step raise this value breaking your short variable's upper limit. |
A: |
We start from:
Execution yields an expected integer output of
|