八种基本类型的包装类

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;
    }
原文地址:https://www.cnblogs.com/zhuxudong/p/10499924.html