Java Number & Math 类
包装类 Number 的继承体系、装箱拆箱与 Math 常用方法。
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
2147483647Integer 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.0Math.round(-3.5) is -3, not -4: it is implemented as floor(x + 0.5). Watch out when rounding negatives.Java Number 类
Byte、Short、Integer、Long、Float、Double 都是抽象类 Number 的子类,提供 intValue()、doubleValue() 等拆箱方法。装箱拆箱由编译器自动完成。
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
2147483647Integer 缓存了 -128~127 的对象,所以 Integer a = 127, b = 127; a == b 为 true,而 128 时为 false。比较包装类内容一律用 equals。Java Math 类
Math 的方法都是 static,直接 Math.xxx() 调用。常用: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.0Math.round(-3.5) 得到 -3 而不是 -4,因为它的实现是 floor(x + 0.5)。负数四舍五入要特别小心。