八種基本類型的包裝類

8種基本類型的包裝類源碼閱讀【屬性值及常用 API 方法使用場景】

Number:數值類型的基類

public abstract class Number implements java.io.Serializable {
    /**
     *  返回指定 Number 的整形值
     */
    public abstract int intValue();

    /**
     *  返回指定 Number 的長整形值
     */
    public abstract long longValue();

    /**
     *  返回指定 Number 的單精度浮點值
     */
    public abstract float floatValue();

    /**
     *  返回指定 Number 的雙精度浮點值
     */
    public abstract double doubleValue();

    /**
     *  返回指定 Number 的字節值
     */
    public byte byteValue() {
        return (byte)intValue();
    }

    /**
     *  返回指定 Number 的短整形值
     */
    public short shortValue() {
        return (short)intValue();
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -8742448824652078965L;
}

Byte

/**
 *  Comparable 接口用於對實現此接口的相同類對象執行排序。
 */
public interface Comparable<T> {
    /**
     *  比較此對象與目標對象 o 的排序
     *  1)返回正值表示大於
     *  2)返回 0 表示等於
     *  3)返回負值表示小於
     */
    int compareTo(T o);
}
  • 屬性說明
/**
 *  Byte 類型封裝了一個原始的 byte 值
 */
public final class Byte extends Number implements Comparable<Byte> {
    /**
     *  byte 類型的最小值
     */
    public static final byte   MIN_VALUE = -128;

    /**
     *  byte 類型的最大值
     */
    public static final byte   MAX_VALUE = 127;

    /**
     *  byte 類型的 Class 對象
     */
    @SuppressWarnings("unchecked")
    public static final Class<Byte> TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");

    /**
     *  此 Byte 對象封裝的原始 byte 值
     */
    private final byte value;

    /**
     *  byte 值所佔據的二進制位數
     */
    public static final int SIZE = 8;

    /**
     *  一個 byte 佔據多少個字節
     */
    public static final int BYTES = SIZE / Byte.SIZE;

}
  • byte 值轉爲 Byte 對象
    /**
     *  Byte 對象緩存池:緩存了 -128 ~ 127 之間的 Byte 對象
     */
    private static class ByteCache {
        private ByteCache(){}
        static final Byte cache[] = new Byte[-(-128) + 127 + 1];
        static {
            for(int i = 0; i < cache.length; i++) {
                cache[i] = new Byte((byte)(i - 128));
            }
        }
    }

    /**
     *  返回代表指定 byte 值的 Byte 對象
     */
    @HotSpotIntrinsicCandidate
    public static Byte valueOf(byte b) {
        final int offset = 128;
        // 直接從緩存中讀取
        return ByteCache.cache[b + offset];
    }
  • 字符串轉 Byte 對象
    /**
     *  將目標字符串轉換爲 Byte 對象
     *
     * @param s 需要解析的字符串
     * @throws NumberFormatException 字符串無法解析爲 Byte
     */
    public static Byte valueOf(String s) throws NumberFormatException {
        return valueOf(s, 10);
    }

    /**
     *  基於指定的基數,將字符串解析爲 Byte 對象
     *
     * @param s 目標字符串
     * @param radix 基數
     * @return
     * @throws NumberFormatException
     */
    public static Byte valueOf(String s, int radix)
            throws NumberFormatException {
        return valueOf(parseByte(s, radix));
    }

    /**
     *  將目標字符串解析爲 byte 值
     * @param s 目標字符串
     * @param radix 解析時使用的基數,一把爲 10 進制
     * @throws NumberFormatException 字符串無法解析爲 byte 值
     */
    public static byte parseByte(String s, int radix)
            throws NumberFormatException {
        final int i = Integer.parseInt(s, radix);
        if (i < MIN_VALUE || i > MAX_VALUE) {
            throw new NumberFormatException(
                    "Value out of range. Value:\"" + s + "\" Radix:" + radix);
        }
        return (byte)i;
    }
  • hashcode 和 equals 方法
    /**
     *  返回此 Byte 對象的哈希值
     */
    @Override
    public int hashCode() {
        return Byte.hashCode(value);
    }

    /**
     *  返回指定 byte 的哈希值
     */
    public static int hashCode(byte value) {
        return value;
    }

    /**
     *  此 Byte 對象是否和目標對象 obj 相等
     *
     * @param obj   待比較的對象
     */
    public boolean equals(Object obj) {
        if (obj instanceof Byte) {
            return value == ((Byte)obj).byteValue();
        }
        return false;
    }
  • Byte 對象和值比較
    /**
     *  比較兩個 Byte 對象的數值
     *
     * @param   anotherByte 待比較的另一個 Byte 對象
     */
    @Override
    public int compareTo(Byte anotherByte) {
        return compare(value, anotherByte.value);
    }

    /**
     *  比較兩個 byte 值 x,y 的大小
     *
     * @param  x    待比較的第一個 byte 值
     * @param  y    待比較的第二個 byte 值
     * @since 1.7
     */
    public static int compare(byte x, byte y) {
        return x - y;
    }

    /**
     *  比較兩個無符號 byte 值的大小
     *
     * @param  x    待比較的第一個 byte 值
     * @param  y    待比較的第二個 byte 值
     * @since 9
     */
    public static int compareUnsigned(byte x, byte y) {
        return Byte.toUnsignedInt(x) - Byte.toUnsignedInt(y);
    }
  • byte 值轉
    /**
     *  將目標 byte 值轉換爲無符號整形值。
     *  1)如果 byte 值爲正數,則返回值與形參一致
     *  2)如果 byte 值爲負數,則返回值爲 x+2^8
     *
     * @param  x    待轉換的 byte 值
     * @since 1.8
     */
    public static int toUnsignedInt(byte x) {
        return x & 0xff;
    }

    /**
     *  將目標 byte 值轉換爲無符號長整形值。
     *  1)如果 byte 值爲正數,則返回值與形參一致
     *  2)如果 byte 值爲負數,則返回值爲 x+2^8
     *
     * @param  x    待轉換的 byte 值
     * @since 1.8
     */
    public static long toUnsignedLong(byte x) {
        return x & 0xffL;
    }

Short

  • 屬性說明
    /**
     *  short 類型的最小值
     */
    public static final short   MIN_VALUE = -32768;

    /**
     *  short 類型的最大值
     */
    public static final short   MAX_VALUE = 32767;

    /**
     *  Short 的 Class 類型
     */
    @SuppressWarnings("unchecked")
    public static final Class<Short>    TYPE = (Class<Short>) Class.getPrimitiveClass("short");

    /**
     * 此對象封裝的 short 值
     */
    private final short value;

    /**
     *  short 值所佔用的二進制 bit 位數
     */
    public static final int SIZE = 16;

    /**
     *  short 值所佔的字節數
     */
    public static final int BYTES = SIZE / Byte.SIZE;
  • 創建 Short 對象
    private static class ShortCache {
        private ShortCache(){}
        // 緩存 -128 - 127 的 Short 對象
        static final Short cache[] = new Short[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++) {
                cache[i] = new Short((short)(i - 128));
            }
        }
    }

    /**
     *  返回代表short 值 s 的 Short 對象,可使用緩存。
     */
    @HotSpotIntrinsicCandidate
    public static Short valueOf(short s) {
        final int offset = 128;
        final int sAsInt = s;
        // 啓用緩存
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }

    /**
     *  將目標字符串 s 按照指定的進制 radix 解析爲 Short 對象
     *
     * @param s 待解析的字符串
     * @param radix 使用的進制數,最小 Character.MIN_RADIX【2】,最大:Character.MAX_RADIX【36】
     */
    public static Short valueOf(String s, int radix)
            throws NumberFormatException {
        return valueOf(parseShort(s, radix));
    }

    /**
     *  將目標字符串 s 按照指定的基數 radix 解析爲在short 值
     * @param s 待解析的字符串
     * @param radix 進制基數
     */
    public static short parseShort(String s, int radix)
            throws NumberFormatException {
        final int i = Integer.parseInt(s, radix);
        if (i < MIN_VALUE || i > MAX_VALUE) {
            throw new NumberFormatException(
                    "Value out of range. Value:\"" + s + "\" Radix:" + radix);
        }
        return (short)i;
    }
  • short 值轉換
    /**
     *  將目標 short 值轉換爲無符號整型值。
     *  1)x 爲正數,則返回其本身
     *  2)x 爲負數,則返回 x+2^16
     *
     * @param  x    待轉換的 short 值
     * @since 1.8
     */
    public static int toUnsignedInt(short x) {
        return x & 0xffff;
    }

    /**
     * 將目標 short 值轉換爲無符號長整型值。
     *  1)x 爲正數,則返回其本身
     *  2)x 爲負數,則返回 x+2^16
     * @since 1.8
     */
    public static long toUnsignedLong(short x) {
        return x & 0xffffL;
    }
  • Short 對象或 short 值比較
    /**
     *  比較兩個 Short 對象的值大小
     *
     * @param   anotherShort    待比較的 Short 對象
     */
    @Override
    public int compareTo(Short anotherShort) {
        return compare(value, anotherShort.value);
    }

    /**
     *  比較兩個 short 值的大小
     *
     * @param  x    第一個待比較的 short 值
     * @param  y    第二個待比較的 short 值
     * @since 1.7
     */
    public static int compare(short x, short y) {
        return x - y;
    }

    /**
     *  先將兩個 short 值轉換爲無符號 short,再進行值比較
     *
     * @param  x    第一個待比較的 short 值
     * @param  y    第二個待比較的 short 值
     * @since 9
     */
    public static int compareUnsigned(short x, short y) {
        return Short.toUnsignedInt(x) - Short.toUnsignedInt(y);
    }

Character

  • 屬性說明
/**
 *  Character 類封裝了一個原始的 char 值。
 *  字符信息以 Unicode Standard version 8.0.0 爲基礎,代碼點範圍 U+0000 to U+10FFFF
 * <ul>
 * <li><a href="http://www.unicode.org">http://www.unicode.org</a>
 * </ul>
 */
public final
class Character implements java.io.Serializable, Comparable<Character> {
    /**
     *  用於字符串解析的最小基數
     */
    public static final int MIN_RADIX = 2;

    /**
     * 用於字符串解析的最大基數
     */
    public static final int MAX_RADIX = 36;

    /**
     *  字符的最小值
     */
    public static final char MIN_VALUE = '\u0000';

    /**
     *  字符的最大值
     */
    public static final char MAX_VALUE = '\uFFFF';

    /**
     *  Character 的 Class 類型值
     */
    @SuppressWarnings("unchecked")
    public static final Class<Character> TYPE = (Class<Character>) Class.getPrimitiveClass("char");

    /**
     *  封裝的原始 char 值
     */
    private final char value;

    /**
     *  一個字符所佔據的二進制 bit 位數
     */
    public static final int SIZE = 16;

    /**
     *  一個字符所佔的字節數
     */
    public static final int BYTES = SIZE / Byte.SIZE;
  • 創建 Character 對象
    private static class CharacterCache {
        private CharacterCache(){}
        static final Character cache[] = new Character[127 + 1];
        static {
            // 緩存 0-128 的字符
            for (int i = 0; i < cache.length; i++) {
                cache[i] = new Character((char)i);
            }
        }
    }

    /**
     *  將目標 char 值封裝爲 Character 對象,可使用緩存
     */
    @HotSpotIntrinsicCandidate
    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[c];
        }
        return new Character(c);
    }
  • 字符類型判斷
    /**
     *  目標字符 ch 是否是數字
     *
     * @param   ch  待測試的目標字符
     */
    public static boolean isDigit(char ch) {
        return isDigit((int)ch);
    }

    /**
     *  判斷指定的 Unicode 代碼點 codePoint 是否是數字
     *
     * @param   codePoint   待測試的 Unicode 代碼點
     */
    public static boolean isDigit(int codePoint) {
        return getType(codePoint) == Character.DECIMAL_DIGIT_NUMBER;
    }

    /**
     *  返回指定 Unicode 代碼點的通用分類
     */
    public static int getType(int codePoint) {
        return CharacterData.of(codePoint).getType(codePoint);
    }

    /**
     *  指定的字符 ch 是否是字母
     *
     * @param   ch  待測試的字符
     */
    public static boolean isLetter(char ch) {
        return isLetter((int)ch);
    }

    /**
     *  判斷指定的 Unicode 代碼點是否是字母
     */
    public static boolean isLetter(int codePoint) {
        return ((1 << Character.UPPERCASE_LETTER |
                1 << Character.LOWERCASE_LETTER |
                1 << Character.TITLECASE_LETTER |
                1 << Character.MODIFIER_LETTER |
                1 << Character.OTHER_LETTER) >> getType(codePoint) & 1)
                != 0;
    }

    /**
     *  判斷指定的字符 ch 是否是小寫字母
     *
     * @param   ch  待測試的字符
     */
    public static boolean isLowerCase(char ch) {
        return isLowerCase((int)ch);
    }

    /**
     *  待測試的 Unicode 代碼點 codePoint 是否是小寫字母
     */
    public static boolean isLowerCase(int codePoint) {
        return getType(codePoint) == Character.LOWERCASE_LETTER ||
                CharacterData.of(codePoint).isOtherLowercase(codePoint);
    }

    /**
     *  目標字符 ch 是否是大寫字母
     *
     * @param   ch  待測試字符
     */
    public static boolean isUpperCase(char ch) {
        return isUpperCase((int)ch);
    }

    /**
     *  待測試的 Unicode 代碼點是否是大寫字母
     *
     * @param   codePoint   待測試的字符
     */
    public static boolean isUpperCase(int codePoint) {
        return getType(codePoint) == Character.UPPERCASE_LETTER ||
                CharacterData.of(codePoint).isOtherUppercase(codePoint);
    }

    /**
     *  判斷指定的字符 ch 是否是空格字符
     *
     * @param   ch  待測試的字符
     */
    public static boolean isSpaceChar(char ch) {
        return isSpaceChar((int)ch);
    }

    /**
     *  判斷指定的 Unicode 代碼點 codePoint 是否是空格字符
     *
     * @param   codePoint   待測試的 Unicode 代碼點
     */
    public static boolean isSpaceChar(int codePoint) {
        return ((1 << Character.SPACE_SEPARATOR |
                1 << Character.LINE_SEPARATOR |
                1 << Character.PARAGRAPH_SEPARATOR) >> getType(codePoint) & 1)
                != 0;
    }

    /**
     *  判斷指定的字符 ch 是否是 Java 空白符
     * @param   ch  待測試的字符
     */
    public static boolean isWhitespace(char ch) {
        return isWhitespace((int)ch);
    }

    /**
     *  判斷指定 Unicode 代碼點是否是 Java 中的空白字符
     * <ul>
     * <li> It is a Unicode space character ({@link #SPACE_SEPARATOR},
     *      {@link #LINE_SEPARATOR}, or {@link #PARAGRAPH_SEPARATOR})
     *      but is not also a non-breaking space ({@code '\u005Cu00A0'},
     *      {@code '\u005Cu2007'}, {@code '\u005Cu202F'}).
     * <li> It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION.
     * <li> It is {@code '\u005Cn'}, U+000A LINE FEED.
     * <li> It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION.
     * <li> It is {@code '\u005Cf'}, U+000C FORM FEED.
     * <li> It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN.
     * <li> It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR.
     * <li> It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR.
     * <li> It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR.
     * <li> It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR.
     * </ul>
     *
     * @param   codePoint   待測試的 Unicode 代碼點
     */
    public static boolean isWhitespace(int codePoint) {
        return CharacterData.of(codePoint).isWhitespace(codePoint);
    }
  • 字符轉換
    /**
     *  將目標字符轉換爲小寫字符
     *
     * @param   ch  待轉換的字符
     */
    public static char toLowerCase(char ch) {
        return (char)toLowerCase((int)ch);
    }

    /**
     *  將目標 Unicode 代碼點轉換爲小寫字符的 Unicode 代碼點
     *
     * @param   codePoint   待轉換的 Unicode 代碼點
     */
    public static int toLowerCase(int codePoint) {
        return CharacterData.of(codePoint).toLowerCase(codePoint);
    }

    /**
     *  將目標字符 ch 轉換爲大寫字符
     *
     * @param   ch  待轉換的目標字符
     */
    public static char toUpperCase(char ch) {
        return (char)toUpperCase((int)ch);
    }

    /**
     *  將目標 Unicode 代碼點轉換爲對應大寫字符的 Unicode 代碼點
     *
     * @param   codePoint   待轉換的 Unicode 代碼點
     */
    public static int toUpperCase(int codePoint) {
        return CharacterData.of(codePoint).toUpperCase(codePoint);
    }

Integer

  • 屬性說明
/**
 *  封裝了原始 int 值的 Integer 對象。
 */
public final class Integer extends Number implements Comparable<Integer> {
    /**
     *  int 類型的最小值
     */
    @Native public static final int   MIN_VALUE = 0x80000000;

    /**
     *  int 類型的最大值
     */
    @Native public static final int   MAX_VALUE = 0x7fffffff;

    /**
     *  int 類型的 Class 對象
     */
    @SuppressWarnings("unchecked")
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

    /**
     *  原始的 int 值
     */
    private final int value;

    /**
     *  int 類型所佔用的二進制 bit 位個數
     */
    @Native public static final int SIZE = 32;

    /**
     *  一個 int 值佔用多少個字節
     */
    public static final int BYTES = SIZE / Byte.SIZE;
}
  • 創建實例
    /**
     *  Integer 緩存
     */
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // 高值可以通過屬性配置
            int h = 127;
            // 讀取名稱爲 java.lang.Integer.IntegerCache.high 的系統變量
            final String integerCacheHighPropValue =
                    VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    // 將其轉換爲整形
                    int i = parseInt(integerCacheHighPropValue);
                    // 取 i 和 127 之間的最大值
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( final NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
            // 創建緩存數組
            cache = new Integer[high - low + 1];
            int j = low;
            // 初始化緩存數組
            for(int k = 0; k < cache.length; k++) {
                cache[k] = new Integer(j++);
            }

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

    /**
     *  返回指定 int 值的封裝對象
     */
    @HotSpotIntrinsicCandidate
    public static Integer valueOf(int i) {
        // 1)嘗試從緩存中讀取
        if (i >= IntegerCache.low && i <= IntegerCache.high) {
            return IntegerCache.cache[i + -IntegerCache.low];
        }
        // 2)如果未命中緩存,則創建新的 Integer 實例
        return new Integer(i);
    }

    /**
     *  將目標字符串 s 解析爲 Integer 對象
     *
     * @param      s    待解析的字符串
     * @exception  NumberFormatException    字符串 s 無法被解析爲 Integer 對象
     */
    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }

    /**
     *  將目標字符串 s 基於指定的基數 radix 解析爲 Integer 對象。
     *
     * <p>Examples:
     * <blockquote><pre>
     * parseInt("0", 10) returns 0
     * parseInt("473", 10) returns 473
     * parseInt("+42", 10) returns 42
     * parseInt("-0", 10) returns 0
     * parseInt("-FF", 16) returns -255
     * parseInt("1100110", 2) returns 102
     * parseInt("2147483647", 10) returns 2147483647
     * parseInt("-2147483648", 10) returns -2147483648
     * parseInt("2147483648", 10) throws a NumberFormatException
     * parseInt("99", 8) throws a NumberFormatException
     * parseInt("Kona", 10) throws a NumberFormatException
     * parseInt("Kona", 27) returns 411787
     * </pre></blockquote>
     *
     * @param      s    待解析的目標字符串
     * @param      radix    進制基數
     */
    public static int parseInt(String s, int radix)
            throws NumberFormatException
    {
        /*
         *  該方法可能在 IntegerCache 初始化之前調用
         */
        if (s == null) {
            throw new NumberFormatException("null");
        }
        // 1)基數小於最小基數
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                    " less than Character.MIN_RADIX");
        }
        // 2)基數大於最大基數
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                    " greater than Character.MAX_RADIX");
        }
        // 正數或負數標識
        boolean negative = false;
        int i = 0;
        // 讀取字符串長度
        final int len = s.length();
        int limit = -Integer.MAX_VALUE;

        if (len > 0) {
            // 讀取第一個字符
            final char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                // 1)如果是負數
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                    // 2)第一個字符如果 < '0' 則該字符只能是 - 或 +
                } else if (firstChar != '+') {
                    throw NumberFormatException.forInputString(s);
                }
                // 3)只有單個 - 或 + 字符
                if (len == 1) { // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                }
                i++;
            }
            final int multmin = limit / radix;
            int result = 0;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                final int digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0 || result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
            return negative ? result : -result;
        } else {
            throw NumberFormatException.forInputString(s);
        }
    }
  • 整數的比較
    /**
     *  比較兩個整數值的大小
     *
     * @param   anotherInteger  待比較的另一個 Integer 對象
     */
    @Override
    public int compareTo(Integer anotherInteger) {
        return compare(value, anotherInteger.value);
    }

    /**
     *  比較兩個整數值 x,y 的大小
     *
     * @param  x    待比較的第一個 int 值
     * @param  y    待比較的第二個 int 值
     * @since 1.7
     */
    public static int compare(int x, int y) {
        return x < y ? -1 : x == y ? 0 : 1;
    }

    /**
     *  將兩個整數值 x,y 轉換爲無符號數,並比較大小
     * @param  x    待比較的第一個 int 值
     * @param  y    待比較的第二個 int 值
     */
    public static int compareUnsigned(int x, int y) {
        return compare(x + MIN_VALUE, y + MIN_VALUE);
    }
  • 整數值計算
    /**
     *  返回 a,b 之間的最大值
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static int max(int a, int b) {
        return Math.max(a, b);
    }

    /**
     *  返回 a,b 之間的最小值
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static int min(int a, int b) {
        return Math.min(a, b);
    }

    /**
     *  計算兩個整數 a,b 的和
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static int sum(int a, int b) {
        return a + b;
    }
  • 從系統變量中讀取指定的整形值
    /**
     *  從系統變量中解碼指定的整形值,不存在則返回 null
     *
     * @param   nm  系統屬性名稱
     */
    public static Integer getInteger(String nm) {
        return getInteger(nm, null);
    }

    /**
     *  讀取指定名稱的系統屬性值,並將其轉換爲 Integer
     *
     * @param   nm  屬性名稱
     * @param   val 默認值
     */
    public static Integer getInteger(String nm, int val) {
        final Integer result = getInteger(nm, null);
        // 讀取失敗,則返回默認值
        return result == null ? Integer.valueOf(val) : result;
    }

    /**
     *  讀取指定名稱的系統屬性,將其轉換爲 Integer 後返回
     *
     * @param   nm  屬性名稱
     * @param   val 默認值
     */
    public static Integer getInteger(String nm, Integer val) {
        String v = null;
        try {
            v = System.getProperty(nm);
        } catch (IllegalArgumentException | NullPointerException e) {
        }
        // 讀取到的系統屬性值不爲 null,則進行解碼
        if (v != null) {
            try {
                return Integer.decode(v);
            } catch (final NumberFormatException e) {
            }
        }
        // 如果沒讀取到值或類型不匹配,則返回默認值
        return val;
    }
  • 將整型值轉換爲指定進制的字符串表示
    /**
     *  將目標整型值轉換爲二進制字符串
     *
     * @param   i   待轉換的整數
     */
    public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
    }

    /**
     *  將目標整形值 i 轉換爲 8 進制字符串
     * @param   i   待轉換的整型值
     */
    public static String toOctalString(int i) {
        return toUnsignedString0(i, 3);
    }

    /**
     *  將目標整形值 i 轉換爲 16 進制字符串
     * @param   i   待轉換的整形值
     */
    public static String toHexString(int i) {
        return toUnsignedString0(i, 4);
    }

Long

  • 屬性說明
/**
 *  封裝了 long 值的 Long 對象
 */
public final class Long extends Number implements Comparable<Long> {
    /**
     *  long 類型的最小值
     */
    @Native public static final long MIN_VALUE = 0x8000000000000000L;

    /**
     *  long 類型的最大值
     */
    @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;

    /**
     *  long 類型的 Class 對象
     */
    @SuppressWarnings("unchecked")
    public static final Class<Long>     TYPE = (Class<Long>) Class.getPrimitiveClass("long");

    /**
     *  封裝的 long 值
     */
    private final long value;

    /**
     *  long 類型佔用的位數
     */
    @Native public static final int SIZE = 64;

    /**
     *  long 類型佔用的字節數
     */
    public static final int BYTES = SIZE / Byte.SIZE;
  • 實例化
    private static class LongCache {
        private LongCache(){}
        // 緩存 -128 ~ 127 之間的 Long 對象
        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++) {
                cache[i] = new Long(i - 128);
            }
        }
    }

    /**
     *  返回指定 long 值的封裝類對象
     */
    @HotSpotIntrinsicCandidate
    public static Long valueOf(long l) {
        final int offset = 128;
        // 1)首先嚐試從緩存中讀取
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        // 2)創建對象並返回其引用
        return new Long(l);
    }

    /**
     *  將目標字符串解析爲 Long 對象
     * @param      s    待解析的字符串
     * @throws     NumberFormatException    字符串無法解析
     */
    public static Long valueOf(String s) throws NumberFormatException
    {
        return Long.valueOf(parseLong(s, 10));
    }

    /**
     *  將目標字符串解析爲 Long 值
     *
     * <blockquote><pre>
     * parseLong("0", 10) returns 0L
     * parseLong("473", 10) returns 473L
     * parseLong("+42", 10) returns 42L
     * parseLong("-0", 10) returns 0L
     * parseLong("-FF", 16) returns -255L
     * parseLong("1100110", 2) returns 102L
     * parseLong("99", 8) throws a NumberFormatException
     * parseLong("Hazelnut", 10) throws a NumberFormatException
     * parseLong("Hazelnut", 36) returns 1356099454469L
     * </pre></blockquote>
     *
     * @param      s    待解析的目標字符串
     * @param      radix    基數
     * @throws     NumberFormatException    字符串無法解析
     */
    public static long parseLong(String s, int radix)
            throws NumberFormatException
    {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        // radix 小於最小基數
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                    " less than Character.MIN_RADIX");
        }
        // radix 大於最大基數
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                    " greater than Character.MAX_RADIX");
        }

        boolean negative = false;
        int i = 0;
        final int len = s.length();
        long limit = -Long.MAX_VALUE;

        if (len > 0) {
            final char firstChar = s.charAt(0);
            // 如果存在 +、- 號
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Long.MIN_VALUE;
                } else if (firstChar != '+') {
                    throw NumberFormatException.forInputString(s);
                }

                if (len == 1) { // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                }
                i++;
            }
            final long multmin = limit / radix;
            long result = 0;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                final int digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0 || result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
            return negative ? result : -result;
        } else {
            throw NumberFormatException.forInputString(s);
        }
    }
  • 從系統屬性中讀取 Long 值
    /**
     *  讀取指定的系統屬性,並將其轉換爲 Long 值。
     *
     * @return  the {@code Long} value of the property.
     * @throws  SecurityException   無權讀取系統屬性
     */
    public static Long getLong(String nm) {
        return getLong(nm, null);
    }

    /**
     *  讀取指定的系統屬性 nm,並將其轉換爲 Long 對象,如果不存在或讀取失敗,則使用默認值 val
     *
     * @param   nm  屬性名稱
     * @param   val 默認值
     * @throws  SecurityException   無權讀取系統屬性
     */
    public static Long getLong(String nm, Long val) {
        String v = null;
        try {
            // 讀取系統屬性
            v = System.getProperty(nm);
        } catch (IllegalArgumentException | NullPointerException e) {
        }
        if (v != null) {
            try {
                // 參數進行解碼
                return Long.decode(v);
            } catch (final NumberFormatException e) {
            }
        }
        // 不存在或解碼失敗,則返回默認值
        return val;
    }

    /**
     * 將目標字符串 nm 解碼爲 Long 對象
     * 
     * <blockquote>
     * <dl>
     * <dt><i>DecodableString:</i>
     * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
     * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
     * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
     * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
     * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
     *
     * <dt><i>Sign:</i>
     * <dd>{@code -}
     * <dd>{@code +}
     * </dl>
     * </blockquote>
     *
     * @param   待解碼的字符串
     * @throws    NumberFormatException 字符串無法解碼
     * @since 1.2
     */
    public static Long decode(String nm) throws NumberFormatException {
        // 默認爲 10 進制格式
        int radix = 10;
        int index = 0;
        boolean negative = false;
        Long result;

        if (nm.length() == 0) {
            throw new NumberFormatException("Zero length string");
        }
        final char firstChar = nm.charAt(0);
        // 嘗試處理符號
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+') {
            index++;
        }

        // 1)如果是 16 進制字符串
        if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        }
        // 2)如果是 16 進制字符串
        else if (nm.startsWith("#", index)) {
            index ++;
            radix = 16;
        }
        // 3)如果是 8 進制字符串
        else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
            index ++;
            radix = 8;
        }

        if (nm.startsWith("-", index) || nm.startsWith("+", index)) {
            throw new NumberFormatException("Sign character in wrong position");
        }

        try {
            // 解碼目標字符串
            result = Long.valueOf(nm.substring(index), radix);
            result = negative ? Long.valueOf(-result.longValue()) : result;
        } catch (final NumberFormatException e) {
            // If number is Long.MIN_VALUE, we'll end up here. The next line
            // handles this case, and causes any genuine format error to be
            // rethrown.
            final String constant = negative ? "-" + nm.substring(index)
            : nm.substring(index);
            result = Long.valueOf(constant, radix);
        }
        return result;
    }
  • 值比較
    /**
     *  比較兩個 long 值的大小
     * @param  x    第一個待比較 long 值
     * @param  y    第二個待比較 long 值
     * @since 1.7
     */
    public static int compare(long x, long y) {
        return x < y ? -1 : x == y ? 0 : 1;
    }

    /**
     *  比較兩個無符號 long 值的大小   
     *
     * @param  x    第一個待比較 long 值
     * @param  y    第二個待比較 long 值
     * @since 1.8
     */
    public static int compareUnsigned(long x, long y) {
        return compare(x + MIN_VALUE, y + MIN_VALUE);
    }

    /**
     *  比較當前對象和目標對象 anotherLong 的值大小
     *
     * @param   anotherLong 待比較的 Long 對象
     * @since   1.2
     */
    @Override
    public int compareTo(Long anotherLong) {
        return compare(value, anotherLong.value);
    }
  • 取值和求和
    /**
     *  讀取兩個 long 值 a,b 的最小值
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static long min(long a, long b) {
        return Math.min(a, b);
    }

    /**
     *  讀取兩個 long 值 a,b 的最大值
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static long max(long a, long b) {
        return Math.max(a, b);
    }

    /**
     *  計算兩個 long 值 a,b 的和
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static long sum(long a, long b) {
        return a + b;
    }
  • 轉換爲字符串表示
    /**
     *  將目標 long 值 i 轉換爲二進制表示
     *
     * @param   i   待轉換的 long 值
     * @since   1.0.2
     */
    public static String toBinaryString(long i) {
        return toUnsignedString0(i, 1);
    }

    /**
     *  將目標 long 值轉換爲 8 進製表示
     *
     * @param   i   待轉換的 long 值
     * @since   1.0.2
     */
    public static String toOctalString(long i) {
        return toUnsignedString0(i, 3);
    }

    /**
     *  將目標 long 值轉換爲 16 進制字符串
     *
     * @param   i   待轉換的 long 值
     * @since   1.0.2
     */
    public static String toHexString(long i) {
        return toUnsignedString0(i, 4);
    }

Float

  • 屬性說明
/**
 *  float 值的封裝類
 */
public final class Float extends Number implements Comparable<Float> {
    /**
     *  正無窮大
     * {@code Float.intBitsToFloat(0x7f800000)}.
     */
    public static final float POSITIVE_INFINITY = 1.0f / 0.0f;

    /**
     *  負無窮大
     * {@code Float.intBitsToFloat(0xff800000)}.
     */
    public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;

    /**
     *  非浮點數
     * {@code Float.intBitsToFloat(0x7fc00000)}.
     */
    public static final float NaN = 0.0f / 0.0f;

    /**
     *  long 類型的最大值
     * {@code Float.intBitsToFloat(0x7f7fffff)}.
     */
    public static final float MAX_VALUE = 0x1.fffffeP+127f; // 3.4028235e+38f

    /**
     * long 類型的一般小值
     * 
     * @since 1.6
     */
    public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f

    /**
     *  long 類型的最小值
     * {@code Float.intBitsToFloat(0x1)}.
     */
    public static final float MIN_VALUE = 0x0.000002P-126f; // 1.4e-45f

    /**
     *  Float 最大的指數
     * Math.getExponent(Float.MAX_VALUE)}.
     *
     * @since 1.6
     */
    public static final int MAX_EXPONENT = 127;

    /**
     *  Float 最小的指數
     * Math.getExponent(Float.MIN_NORMAL)}.
     *
     * @since 1.6
     */
    public static final int MIN_EXPONENT = -126;

    /**
     *  float 類型佔據的位數
     */
    public static final int SIZE = 32;

    /**
     *  float 類型佔據的字節數
     * @since 1.8
     */
    public static final int BYTES = SIZE / Byte.SIZE;

    /**
     *  float 類型的 Class 對象
     * @since 1.1
     */
    @SuppressWarnings("unchecked")
    public static final Class<Float> TYPE = (Class<Float>) Class.getPrimitiveClass("float");

    /**
     *  封裝的 float 值
     */
    private final float value;
  • 實例化
    /**
     *  返回指定 float 值 f 的封裝類對象
     *
     * @param  f    目標 float 值
     * @since  1.5
     */
    @HotSpotIntrinsicCandidate
    public static Float valueOf(float f) {
        return new Float(f);
    }

    /**
     *  將目標字符串 s 解析爲 Float 對象
     *
     * @param   s   待解析的字符串
     * @throws  NumberFormatException   字符串無法解析
     */
    public static Float valueOf(String s) throws NumberFormatException {
        return new Float(parseFloat(s));
    }

    /**
     *  將目標字符串 s 解析爲 float 值
     * @since 1.2
     */
    public static float parseFloat(String s) throws NumberFormatException {
        return FloatingDecimal.parseFloat(s);
    }
  • 比較
    /**
     *  比較兩個 float 值 f1,f2 的大小
     *
     * @param   f1  第一個待比較的 float 值
     * @param   f2  第二個待比較的 float 值
     * @since 1.4
     */
    public static int compare(float f1, float f2) {
        if (f1 < f2)
        {
            return -1;           // Neither val is NaN, thisVal is smaller
        }
        if (f1 > f2)
        {
            return 1;            // Neither val is NaN, thisVal is larger
        }

        // Cannot use floatToRawIntBits because of possibility of NaNs.
        // 將浮點數轉換爲整形 bit
        final int thisBits    = Float.floatToIntBits(f1);
        final int anotherBits = Float.floatToIntBits(f2);

        return thisBits == anotherBits ?  0 : // Values are equal
            thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
                1;                          // (0.0, -0.0) or (NaN, !NaN)
    }

    /**
     *  比較當前 Float 對象和目標 Float 對象 anotherFloat 的大小
     *
     * @param   anotherFloat    待比較的 Float 對象
     * @since   1.2
     */
    @Override
    public int compareTo(Float anotherFloat) {
        return Float.compare(value, anotherFloat.value);
    }
  • 取值和求和
    /**
     *  返回兩個 float a,b 的最小值
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static float min(float a, float b) {
        return Math.min(a, b);
    }

    /**
     *  返回兩個 float a,b 的最大值
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static float max(float a, float b) {
        return Math.max(a, b);
    }

    /**
     *  返回兩個 float a,b 的和
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static float sum(float a, float b) {
        return a + b;
    }
  • float 轉換
    /**
     *  將 float 值轉換爲 int
     * @param   value   浮點數
     */
    @HotSpotIntrinsicCandidate
    public static int floatToIntBits(float value) {
        if (!isNaN(value)) {
            return floatToRawIntBits(value);
        }
        return 0x7fc00000;
    }

    /**
     *  將整型值轉換爲 float 值
     *
     * <p>If the argument is {@code 0x7f800000}, the result is positive
     * infinity.
     *
     * <p>If the argument is {@code 0xff800000}, the result is negative
     * infinity.
     *
     * <p>If the argument is any value in the range
     * {@code 0x7f800001} through {@code 0x7fffffff} or in
     * the range {@code 0xff800001} through
     * {@code 0xffffffff}, the result is a NaN. 
     *
     * @param   bits    待轉換的整形值
     */
    @HotSpotIntrinsicCandidate
    public static native float intBitsToFloat(int bits);
  • 轉換爲字符串
    /**
     *  浮點值轉換爲 16 進制字符串
     *
     * @param   f   待轉換的 float 值
     * @since 1.5
     * @author Joseph D. Darcy
     */
    public static String toHexString(float f) {
        if (Math.abs(f) < Float.MIN_NORMAL
                &&  f != 0.0f ) {// float subnormal
            // Adjust exponent to create subnormal double, then
            // replace subnormal double exponent with subnormal float
            // exponent
            final String s = Double.toHexString(Math.scalb((double)f,
                    /* -1022+126 */
                    Double.MIN_EXPONENT-
                    Float.MIN_EXPONENT));
            return s.replaceFirst("p-1022$", "p-126");
        } else {
            return Double.toHexString(f);
        }
    }

Double

  • 屬性說明
/**
 *  封裝了 double 值的 Double 對象
 * @since 1.0
 */
public final class Double extends Number implements Comparable<Double> {
    /**
     *  正無窮大
     * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
     */
    public static final double POSITIVE_INFINITY = 1.0 / 0.0;

    /**
     *  負無窮大
     * {@code Double.longBitsToDouble(0xfff0000000000000L)}.
     */
    public static final double NEGATIVE_INFINITY = -1.0 / 0.0;

    /**
     *  非數字
     * {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
     */
    public static final double NaN = 0.0d / 0.0;

    /**
     *  double 的最大值
     * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
     */
    public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308

    /**
     *  double 的一般小值
     * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}.
     *
     * @since 1.6
     */
    public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308

    /**
     *  double 的最小值
     * {@code Double.longBitsToDouble(0x1L)}.
     */
    public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324

    /**
     *  double 的最大指數值
     * {@code Math.getExponent(Double.MAX_VALUE)}.
     *
     * @since 1.6
     */
    public static final int MAX_EXPONENT = 1023;

    /**
     *  double 的最小指數值
     * {@code Math.getExponent(Double.MIN_NORMAL)}.
     *
     * @since 1.6
     */
    public static final int MIN_EXPONENT = -1022;

    /**
     *  double 類型佔據的位數
     * @since 1.5
     */
    public static final int SIZE = 64;

    /**
     *  double 類型佔據的字節數
     * @since 1.8
     */
    public static final int BYTES = SIZE / Byte.SIZE;

    /**
     *  double 類型的 Class 對象
     * @since 1.1
     */
    @SuppressWarnings("unchecked")
    public static final Class<Double>   TYPE = (Class<Double>) Class.getPrimitiveClass("double");

    /**
     *  封裝的 double 值
     */
    private final double value;
  • 實例化
    /**
     *  返回指定 double 值 d 的封裝類
     *
     * @param  d    目標 double 值
     * @since  1.5
     */
    @HotSpotIntrinsicCandidate
    public static Double valueOf(double d) {
        return new Double(d);
    }

    /**
     *  將字符串 s 解析爲 Double 對象
     *
     * @param      s    待解析的字符串
     * @throws     NumberFormatException    字符串無法解析
     */
    public static Double valueOf(String s) throws NumberFormatException {
        return new Double(parseDouble(s));
    }
  • 比較
    /**
     *  比較兩個 double 值 d1,d2 的大小
     *
     * @param   d1  第一個待比較的 double 值
     * @param   d2  第二個待比較的 double 值
     * @since 1.4
     */
    public static int compare(double d1, double d2) {
        if (d1 < d2)
        {
            return -1;           // Neither val is NaN, thisVal is smaller
        }
        if (d1 > d2)
        {
            return 1;            // Neither val is NaN, thisVal is larger
        }

        // Cannot use doubleToRawLongBits because of possibility of NaNs.
        // double 值轉換爲 long
        final long thisBits    = Double.doubleToLongBits(d1);
        final long anotherBits = Double.doubleToLongBits(d2);

        return thisBits == anotherBits ?  0 : // Values are equal
            thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
                1;                          // (0.0, -0.0) or (NaN, !NaN)
    }

    /**
     *  比較此對象與另一個 Double 對象 anotherDouble 的大小
     *
     * @param   anotherDouble   待比較的 Double 對象
     * @since   1.2
     */
    @Override
    public int compareTo(Double anotherDouble) {
        return Double.compare(value, anotherDouble.value);
    }
  • 取值和求和
    /**
     *  返回兩個 double 值 a,b 的最小值
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static double min(double a, double b) {
        return Math.min(a, b);
    }

    /**
     *  返回兩個 double 值 a,b 的最大值
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static double max(double a, double b) {
        return Math.max(a, b);
    }

    /**
     *  返回兩個 double 值 a,b 的和
     *
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static double sum(double a, double b) {
        return a + b;
    }
  • double 和 long 的轉換
    /**
     *  double 值轉換爲 long
     * @param   value   double 值
     */
    @HotSpotIntrinsicCandidate
    public static long doubleToLongBits(double value) {
        if (!isNaN(value)) {
            return doubleToRawLongBits(value);
        }
        return 0x7ff8000000000000L;
    }

    /**
     *  long 值轉換爲 double
     *
     * @param   bits    long 值
     */
    @HotSpotIntrinsicCandidate
    public static native double longBitsToDouble(long bits);
  • double 轉換爲 16 進制字符串
    /**
     *  double 值轉換爲 16 進制字符串
     *
     * @param   d   待轉換的 double 值
     * @since 1.5
     * @author Joseph D. Darcy
     */
    public static String toHexString(double d) {
        /*
         * Modeled after the "a" conversion specifier in C99, section
         * 7.19.6.1; however, the output of this method is more
         * tightly specified.
         */
        if (!isFinite(d) ) {
            // For infinity and NaN, use the decimal output.
            return Double.toString(d);
        } else {
            // Initialized to maximum size of output.
            final StringBuilder answer = new StringBuilder(24);

            if (Math.copySign(1.0, d) == -1.0)
            {
                answer.append("-");                  // so append sign info
            }

            answer.append("0x");

            d = Math.abs(d);

            if(d == 0.0) {
                answer.append("0.0p0");
            } else {
                final boolean subnormal = d < Double.MIN_NORMAL;

                // Isolate significand bits and OR in a high-order bit
                // so that the string representation has a known
                // length.
                final long signifBits = Double.doubleToLongBits(d)
                        & DoubleConsts.SIGNIF_BIT_MASK |
                        0x1000000000000000L;

                // Subnormal values have a 0 implicit bit; normal
                // values have a 1 implicit bit.
                answer.append(subnormal ? "0." : "1.");

                // Isolate the low-order 13 digits of the hex
                // representation.  If all the digits are zero,
                // replace with a single 0; otherwise, remove all
                // trailing zeros.
                final String signif = Long.toHexString(signifBits).substring(3,16);
                answer.append(signif.equals("0000000000000") ? // 13 zeros
                        "0":
                            signif.replaceFirst("0{1,12}$", ""));

                answer.append('p');
                // If the value is subnormal, use the E_min exponent
                // value for double; otherwise, extract and report d's
                // exponent (the representation of a subnormal uses
                // E_min -1).
                answer.append(subnormal ?
                        Double.MIN_EXPONENT:
                            Math.getExponent(d));
            }
            return answer.toString();
        }
    }

Boolean

  • 屬性說明
/**
 *  boolean 值的封裝類
 * @author  Arthur van Hoff
 * @since   1.0
 */
public final class Boolean implements java.io.Serializable,
                                      Comparable<Boolean>
{
    /**
     *  原始 true 值的封裝類
     */
    public static final Boolean TRUE = new Boolean(true);

    /**
     *  原始 false 值的封裝類
     */
    public static final Boolean FALSE = new Boolean(false);

    /**
     *  boolean 類型的 Class 對象
     * @since   1.1
     */
    @SuppressWarnings("unchecked")
    public static final Class<Boolean> TYPE = (Class<Boolean>) Class.getPrimitiveClass("boolean");

    /**
     *  原始 boolean 值
     */
    private final boolean value;
  • 實例化
    /**
     *  返回 boolean 值 b 的封裝類對象
     *
     * @param  b    原始 boolean 值
     * @since  1.4
     */
    @HotSpotIntrinsicCandidate
    public static Boolean valueOf(boolean b) {
        return b ? TRUE : FALSE;
    }

    /**
     *  將目標字符串 s 轉換爲 Boolean 對象
     *
     * @param   s   目標字符串
     */
    public static Boolean valueOf(String s) {
        return parseBoolean(s) ? TRUE : FALSE;
    }

    public static boolean parseBoolean(String s) {
        return "true".equalsIgnoreCase(s);
    }
  • 讀取系統屬性的值
    /**
     *  讀取系統屬性 name 的值並將其轉換爲 boolean 值
     *  屬性值不存在或解析失敗爲 false
     *
     * @param   name    系統屬性名稱
     */
    public static boolean getBoolean(String name) {
        boolean result = false;
        try {
            result = parseBoolean(System.getProperty(name));
        } catch (IllegalArgumentException | NullPointerException e) {
        }
        return result;
    }
  • 比較
    /**
     *  比較兩個 boolean 值 x,y 的大小
     *
     * @param  x    待比較的第一個 boolean 值
     * @param  y    待比較的第二個 boolean 值
     * @since 1.7
     */
    public static int compare(boolean x, boolean y) {
        // 左側值優先
        return x == y ? 0 : x ? 1 : -1;
    }

    /**
     *  比較此對象與目標 Boolean 對象 b 的大小
     * @throws  NullPointerException    目標參數爲 null
     * @since  1.5
     */
    @Override
    public int compareTo(Boolean b) {
        return compare(value, b.value);
    }
  • 邏輯運算
    /**
     *  邏輯與操作
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static boolean logicalAnd(boolean a, boolean b) {
        return a && b;
    }

    /**
     *  邏輯或操作
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static boolean logicalOr(boolean a, boolean b) {
        return a || b;
    }

    /**
     *  邏輯異或操作
     * @param a 第一個操作數
     * @param b 第二個操作數
     * @since 1.8
     */
    public static boolean logicalXor(boolean a, boolean b) {
        return a ^ b;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章