(^104) | Arithmetic Expressions
byte
short
int
long
8 bits
16 bits
3 2 bits
6 4 bits
Figure 3.4 TheiIntegral types in Java
The inttype is, by far, the most common data type for manipulating integer data. The
byteand shorttypes are used far less frequently. In Java you nearly always use intfor ma-
nipulating integer values, but sometimes you may use longif your application requires val-
ues larger than the maximum intvalue. The range of intvalues is from –2147483648through
+2147483647. As noted in Chapter 1, numbers like these remind us that the binary number sys-
tem is working in the background.
A variable of type intcan hold any value with up to 9 decimal digits, such as a Social
Security number. For values with more digits, such as a telephone number with country and
area codes, this type isn’t large enough. Such numbers require the longtype, which can hold
any integer up to 18 digits in length.
When you write a literal integer value, Java automatically assumes that it is of type int.
To write a literal of type long, you must follow the last digit of the number with the letter “L”.
You may also use the lowercase “l”, but it looks so much like the digit “ 1 ” that it may be im-
possible for a person to recognize the literal as longwhen reading your code. We use only the
uppercase “L” in this text. Here are some examples of literals of type intand long:
Literal Type
0 int
0L long
2001 int
18005551212L long
18005551212 invalid (11 digits are too many for the type int)
If your code tries to compute a value larger than a type’s maximum value, it results in
integer overflow. Some programming languages give you an error message when overflow
occurs, but Java doesn’t. If a computation in Java produces a value that is too large for the type
to represent, you simply get an erroneous result.
やまだぃちぅ
(やまだぃちぅ)
#1