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; // Wideningdouble 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. 26
int and char
|
Q: |
Explain the following output:
Why do we see a result of 65535 rather than -1? TipReconsider 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 (underflow)
subtract operation. The beginning 10000 0000 0000 0000 - 0000 0000 0000 0001 ————————————————————— 01111 1111 1111 1111 |
||||||||||||||||
No. 27
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. 28
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. 29
Get a byte from 139
|
Q: |
Consider: Explain in detail why execution results in a value of
|
|
A: |
A four byte Since byte values in Java™ are being represented as signed values in eight bit two-complement notation this equals decimal -117. |
