Java Number & Math 类

包装类 Number 的继承体系、装箱拆箱与 Math 常用方法。

Beginner
Key Points八个基本类型都有包装类,都继承 Number(char/boolean 除外);Math 全是静态方法,round 是四舍五入但返回 long。

Java Number 类

Byte, Short, Integer, Long, Float and Double all extend the abstract Number class, which offers unboxing methods like intValue() and doubleValue(). Boxing and unboxing are automatic.

Java
public class NumberDemo {
    public static void main(String[] args) {
        Integer a = 100;          // 自动装箱
        int b = a;                // 自动拆箱

        Number n = 3.14;
        System.out.println(b);
        System.out.println(n.intValue());
        System.out.println(n.doubleValue());

        System.out.println(Integer.parseInt("42"));
        System.out.println(Integer.toBinaryString(10));
        System.out.println(Integer.MAX_VALUE);
    }
}
Output
100
3
3.14
42
1010
2147483647
Integer caches -128..127, so Integer a = 127, b = 127; a == b is true but false at 128. Always compare wrapper values with equals.

Java Math 类

Every Math method is static, called as Math.xxx(). The everyday set: abs, max, min, pow, sqrt, round, ceil, floor, random.

Java
public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-5));
        System.out.println(Math.max(3, 7));
        System.out.println(Math.min(3, 7));
        System.out.println(Math.pow(2, 10));
        System.out.println(Math.sqrt(16));
        System.out.println(Math.round(3.5));
        System.out.println(Math.round(-3.5));
        System.out.println(Math.ceil(3.1));
        System.out.println(Math.floor(3.9));
    }
}
Output
5
7
3
1024.0
4.0
4
-3
4.0
3.0
Math.round(-3.5) is -3, not -4: it is implemented as floor(x + 0.5). Watch out when rounding negatives.

Friends & Partners