Primitive types
Literal | Discriminator | Type | Value |
---|---|---|---|
29 |
base 10 |
Decimal | |
0b11101 | 0b, base 2 | Binary |
|
0x1D | 0x, base 16 | Hexadecimal | |
035 | 0, base 8 | Octal |
No. 6
Literal samples
Q: |
Create code printing an example for each type of literal in Java. TipYou may follow Java Literals. |
A: |
|
No. 7
Literals of type int
Q: |
Calculate the above sample values in decimal beforehand. Then write and execute code printing the above values. |
||||||||||||||||||||
A: |
Manual calculation: 0B11011 = 16 + 8 + 0 + 2 + 1 = 27 037 = 3 * 8 + 7 = 31 123 = 123 0X2F = 2 * 16 + F = 2 * 16 + 15 = 47 Code execution:
|
No. 8
Integer overflow
Q: |
Execute the following code:
Whats wrong here? How can we achieve the desired output? Tip
|
A: |
The code snippet fails with an »Integer number too large« error. In Java™ 3123424234 is a literal of
type System.out.println(3123424234L); |
No. 9
Strange sum result
Q: |
Execute the following code:
Explain the result. TipConsider the |
A: |
2147483647 or is the largest possible int value being allowed in four byte (=32 bit) two complement representation. It is thus perfectly clear that adding this value to itself will result in an arithmetic failure. Execution yields a surprising value of -2. This is due to an
overflow error: Java™ uses the aforementioned
four byte two-complement representation for 01111111_11111111_11111111_11111111 + 01111111_11111111_11111111_11111111 _____________________________________ 11111111_11111111_11111111_11111110 This is the four-byte 2-complement representation of -2. It actually is a sign bit interference: Lets pretend we were having just a 31 bit unsigned representation rather than 32 bit two complement. The very same sum would then simply yield an overflow: 1111111_11111111_11111111_11111111
+ 1111111_11111111_11111111_11111111
_____________________________________
11111111_11111111_11111111_11111110 In 31 bit representation the leftmost »red« bit would be discarded leaving us with an incorrect value of 2147483646 or as well. But in 32 bit 2-complement representation the leftmost bit represents the sign. It gets overwritten by the arithmetic overflow yielding an even negative result. |
No. 10
Correcting the error
Q: |
How do we correct the erroneous outcome in Strange sum result ? TipConsider related Java™ literals. |
||||
A: |
We may simply replace
In Figure 113, “Binary operator type examples ” we'll
learn that the sum of two Literals of type |