http://www.leepoint.net/notes-java/data/basic_types/21integers.html
Four (or five) kinds of primtive integers and two integer classes.
Primitive types. The are four types of integers in Java:byte
,
short
, int
, long
.
The most common is int. All integers are stored in signed, two's-complement, format.
char! Technically, char
is an unsigned integer type altho it is almost exclusively used to store characters. Making it integer is largely because of Java's legacy from C++. Don't use
char
for integers unless you are sure of what you're doing.
Classes. In addition to the primitive types, there are two classes used for integers.
- Integer - Primarily useful for utility methods and to put in the Collections data structure classes.
- BigInteger - Used where unbounded arithmetic is important.
How Java stores integers in memory
Java stores all integers in memory as binary numbers.
type | Size | Range | ||
name | bytes | bits | minimum | maximum |
byte | 1 | 8 | -128 | +127 |
short | 2 | 16 | -32,768 | +32,767 |
int | 4 | 32 | -2,147,483,648 | +2,147,483,647 |
long | 8 | 64 | -9,223,372,036,854,775,808 |
+9,223,372,036,854,775,807 |
2.http://nannan408.iteye.com/blog/1255315
int和long都是很循规蹈矩的符合2的n次方的说法,int是32位,long是64位,唯有float和double像两个淘气的小孩子让人会捉摸不透。float和double的表示形式与int和long是不一样的,他们采用的是IEEE 754标准,这个标准可以这样理解:
(1)两者还是32位的,和int一样,最小值只是他们的精度,是正数,这是需要注意的。如果要取到他们负最大,在他们的最大值前加个符号就好了,如-Float.MAX_VALUE,就是float能表示的负的最大了。
(2)float从左到右,第一位是符号位,2-9位共8位表示整数位,2的8-1次方等于128,后面23位是表示小数的,所以最大值是2^128-1;
(3)double从左到右,第一位是符号位,2-12是共11位表示整数位,2的11-1次方等于1024。剩余20位表示小数,所以最大值是2^1024-1.
(4)如上面代码,当正的最大减去负的正最大,就产生了内存泄露。溢出的结果是不对的。
总结:int 和long,float和double的存储要分别对待.要取到实实在在的最大最小值,只需要取到最大值就行了。