第一天,java的基本数据类型

public class BaseDTTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{

		int y=10;
		
		int x=0;
		
		do
		{
			y--;
			
			x++;
			
		}while(y<10);
		
		System.out.println(x);
	}

}

 此题简单,但是尴尬的不记得各基本数据类型最大值和最小值的就悲催了。如下:

                                                                                                   
基本类型 大小 最大值 最小值 包装类
char 16-bit unicode 0 unicode 2^16-1 Character
byte 8bits -128 +127 Byte
short 16bits -2^15 +2^15-1 Short
int 32bits -2^31 +2^31-1 Integer
long 64bits ... ... Long
float 32bits IEEE754 IEEE754 Float
double 64bits IEEE754 IEEE754 Double

IEEE754是二进制浮点数算术标准,找下维基百科吧。

JDK1.5后基本类型与包装类之间有自动拆装箱,不用程序员显式的转换.前几天翻JDK的代码发现

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

 除了float、double其他基本类型都有缓存

    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }
    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }
    public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }
    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

以上搞清楚后,下面这个问题就简单明了了

	public static void main(String[] args)
	{
		Integer a=1;
		
		Integer b=2;
		
		Integer c=3;
		
		Integer d=3;
		
		Integer e=321;
		
		Integer f=321;
		
		Long g=3L;
		
		System.out.println(c==d);
		
		System.out.println(e==f);
		
		System.out.println(c==(a+b));
		
		System.out.println(c.equals(a+b));
		
		System.out.println(g==(a+b));
		
		System.out.println(g.equals(a+b));

	}

总结是逐步的,还请大家轻拍。

猜你喜欢

转载自advance-t.iteye.com/blog/1758149