Java Reference
In-Depth Information
As a consequence of how we've defined things, in this repre‐
sentation we have a very simple way to identify whether a bit
pattern corresponds to a negative number: if the high-end bit
of a bit pattern is a 1 , then the number being represented is
Consider the bit pattern consisting of all set bits: 0b1111_1111 . If we add 1 to this
number, then the result will overflow the 8 bits of storage that a byte has, resulting
in 0b1_0000_0000 . If we want to constrain this to fit within the byte data type, then
we should ignore the overflow, so this becomes 0b0000_0000 - zero. It is therefore
natural to adopt the representation that “all set bits is -1 .” This allows for natural
arithmetic behavior, like this:
b = ( byte ) 0 b1111_1111 ; // -1
System . out . println ( b );
b ++;
System . out . println ( b );
b = ( byte ) 0 b1111_1110 ; // -2
System . out . println ( b );
b ++;
System . out . println ( b );
Finally, let's look at the number that 0b1000_0000 represents. It's the most negative
number that the type can represent, so for byte :
b = ( byte ) 0 b1000_0000 ;
System . out . println ( b ); // -128
This representation is called two's complement , and is the most common representa‐
tion for signed integers. To use it effectively, there are only two points that you need
to remember:
• A bit pattern of all 1's is the representation for -1.
• If the high bit is set, the number is negative.
Java's other integer types ( short , int , and long ) behave in very similar ways but
with more bits in their representation. The char datatype is different because it rep‐
resents a Unicode character, but in some ways behaves as an unsigned 16-bit
numeric type. It is not normally regarded as an integer type by Java programmers.
Java and Floating-Point Numbers
Computers represent numbers using binary. We've seen how Java uses the two's
complement representation for integers. But what about fractions or decimals? Java,
like almost all modern programming languages, represents them using loating-
point arithmetic . Let's take a look at how this works, first in base-10 (regular deci‐
mal) and then in binary. Java defines the two most important mathematical con‐
stants, e and π as constants in java.lang.Math like this:
Search WWH ::

Custom Search