Java常用类核心详解(一):Math 类超细讲解

🏠个人主页:黎雁

🎬作者简介:C/C++/JAVA后端开发学习者

❄️个人专栏:C语言、数据结构(C语言)、EasyX、JAVA、游戏、规划、程序人生

✨ 从来绝巘须孤往,万里同尘即玉京

文章目录

  • [Java常用类核心详解(一):Math 类超细讲解 ✨](#Java常用类核心详解(一):Math 类超细讲解 ✨)
    • [📚 知识回顾](#📚 知识回顾)
    • [📝 文章摘要](#📝 文章摘要)
    • [1. Math 类概述 🧮](#1. Math 类概述 🧮)
    • [2. 常用方法一览表 📋](#2. 常用方法一览表 📋)
    • [3. 方法细节 + 代码逐行讲解 💻](#3. 方法细节 + 代码逐行讲解 💻)
      • [3.1 绝对值:abs() / absExact()](#3.1 绝对值:abs() / absExact())
      • [3.2 向上取整 ceil()](#3.2 向上取整 ceil())
      • [3.3 向下取整 floor()](#3.3 向下取整 floor())
      • [3.4 四舍五入 round()](#3.4 四舍五入 round())
      • [3.5 最大/最小、幂、开方](#3.5 最大/最小、幂、开方)
      • [3.6 随机数 random() 🔥(高频面试/开发)](#3.6 随机数 random() 🔥(高频面试/开发))
    • [4. 完整测试代码 ✅](#4. 完整测试代码 ✅)
    • [📌 重点总结(面试必背)](#📌 重点总结(面试必背))
    • [✍️ 写在最后](#✍️ 写在最后)

Java常用类核心详解(一):Math 类超细讲解 ✨

本文属于 Java 常用类核心精讲系列,持续更新中~

📚 知识回顾

在正式学习之前,我们先快速回顾一下前置知识点:

  • Java 中 工具类 一般是 final 修饰、构造方法私有、方法全部静态
  • java.lang 包下的类使用时不需要导包
  • 静态方法直接通过 类名.方法名 调用

📝 文章摘要

  • 文章主题 :Java 中 Math 数学工具类详解,包含常用方法、源码细节、坑点、实战案例
  • 阅读时长:8 分钟
  • 适合人群 :
    • Java 零基础小白:掌握数学计算 API,告别手写复杂逻辑
    • 初中级开发:系统梳理 Math 类,避开精度与边界坑点
    • 面试备考者:熟记 abs 边界问题、取整规则、随机数生成
  • 阅读重点 :
    1. Math 类设计思想(工具类、不可继承、私有构造)
    2. 常用方法用法与区别
    3. abs 与 absExact 底层差异与 Integer 最小值坑点
    4. 向上取整、向下取整、四舍五入规则
    5. 随机数 [1, 100] 标准写法

1. Math 类概述 🧮

Math 是 Java 内置的数学运算工具类,提供大量常用数学计算方法,不用重复造轮子。

核心特点

  • 位于 java.lang 包,不用导包
  • 被 public final 修饰,不能被继承
  • 构造方法私有,不能创建对象
  • 所有方法都是 static 静态,直接类名调用
  • 内置两个常用常量:
    • Math.E:自然对数底数 ≈ 2.71828
    • Math.PI:圆周率 ≈ 3.14159

2. 常用方法一览表 📋

方法签名 功能说明
public static int abs(int a) 取绝对值(无越界判断)
public static int absExact(int a) 取绝对值(有越界判断,JDK15+)
public static double ceil(double a) 向上取整(进一法)
public static double floor(double a) 向下取整(去尾法)
public static int round(float a) 四舍五入
public static int max(int a,int b) 取两数较大值
public static int min(int a,int b) 取两数较小值
public static double pow(double a,double b) a 的 b 次幂
public static double sqrt(double a) 平方根
public static double cbrt(double a) 立方根
public static double random() 生成 [0.0, 1.0) 随机数

3. 方法细节 + 代码逐行讲解 💻

3.1 绝对值:abs() / absExact()

重点:Integer 最小值坑点!

java 复制代码
// 普通情况
System.out.println(Math.abs(88));   // 88
System.out.println(Math.abs(-88));  // 88

// 🔥 重点坑:int 范围 -2147483648 ~ 2147483647
// -2147483648 没有对应的正数,abs 会直接返回负数!
System.out.println(Math.abs(-2147483648)); // -2147483648(bug)

// absExact 会判断并抛出异常,更安全
// System.out.println(Math.absExact(-2147483648)); // 抛出 ArithmeticException

absExact 源码思想:

java 复制代码
public static int absExact(int a) {
    if (a == Integer.MIN_VALUE)
        throw new ArithmeticException("溢出");
    else
        return abs(a);
}

✅ 开发建议:对整数取绝对值优先用 absExact,避免隐藏 bug。


3.2 向上取整 ceil()

向数轴正方向进一

java 复制代码
System.out.println(Math.ceil(12.34));  // 13.0
System.out.println(Math.ceil(-12.34)); // -12.0

3.3 向下取整 floor()

向数轴负方向进一

java 复制代码
System.out.println(Math.floor(12.34));  // 12.0
System.out.println(Math.floor(-12.34)); // -13.0

3.4 四舍五入 round()

java 复制代码
System.out.println(Math.round(12.34));  // 12
System.out.println(Math.round(12.54));  // 13
System.out.println(Math.round(-12.34)); // -12
System.out.println(Math.round(-12.54)); // -13

3.5 最大/最小、幂、开方

java 复制代码
// 最大最小
System.out.println(Math.max(20, 30)); // 30
System.out.println(Math.min(20, 30)); // 20

// 幂运算
System.out.println(Math.pow(2, 3));   // 8.0

// 平方根 & 立方根
System.out.println(Math.sqrt(4)); // 2.0
System.out.println(Math.cbrt(8)); // 2.0

3.6 随机数 random() 🔥(高频面试/开发)

需求:生成 1, 100 之间的随机整数。

java 复制代码
// 标准公式:(int)(Math.random() * 范围 + 起始)
for (int i = 0; i < 10; i++) {
    int num = (int) (Math.random() * 100 + 1);
    System.out.print(num + " ");
}

推导过程:

  • Math.random() → [0.0, 1.0)
  • * 100 → [0.0, 100.0)
  • +1 → [1.0, 101.0)
  • 强转 int → [1, 100]

4. 完整测试代码 ✅

java 复制代码
public class MathDemo1 {
    public static void main(String[] args) {
        // 1. 绝对值
        System.out.println(Math.abs(-88));
        System.out.println(Math.abs(-2147483648));
        // System.out.println(Math.absExact(-2147483648));

        // 2. 取整
        System.out.println(Math.ceil(12.34));
        System.out.println(Math.floor(12.34));
        System.out.println(Math.round(12.54));

        // 3. 最大最小
        System.out.println(Math.max(20, 30));
        System.out.println(Math.min(20, 30));

        // 4. 幂与开方
        System.out.println(Math.pow(2, 3));
        System.out.println(Math.sqrt(4));
        System.out.println(Math.cbrt(8));

        // 5. 随机数 [1,100]
        for (int i = 0; i < 10; i++) {
            System.out.print((int) (Math.random() * 100 + 1) + " ");
        }
    }
}

📌 重点总结(面试必背)

  1. Math 是 工具类,不能继承、不能 new,全是静态方法
  2. abs(-2147483648) 会返回负数,优先使用 absExact
  3. ceil 向上、floor 向下、round 四舍五入
  4. 随机数 [a,b] 公式:(int)(Math.random()*(b-a+1)+a)
  5. 常用常量:Math.PI、Math.E

✍️ 写在最后

本篇把 Math 类 从结构、方法、坑点、实战一次性讲透,是 Java 基础中高频使用、面试常问的模块。

下一篇我们将学习 System 类,包括:

  • 系统时间戳(性能统计)
  • 数组拷贝 arraycopy
  • 退出 JVM exit
相关推荐
学到老活到老9 分钟前
第 22 集:Filter、Interceptor、AOP 都能拦截,为什么不能互换?
java·后端·spring
lusklusklusk23 分钟前
Python 全局变量与局部变量区别——global 关键字、__main__ 块与作用域示例
开发语言·前端·python
sun032234 分钟前
【JDK 动态代理】 和 【CGLIB 代理】对比
java·数据库·sql
文丑颜不良啊34 分钟前
LeetCode1261~1280题目解析
java·leetcode
郭小李36 分钟前
spring 中的 @EnableWebMvc注解和WebMvcConfigurer接口
java·后端·spring
马剑威(威哥爱编程)37 分钟前
Python 智能体开发实战 01:装了三遍环境还在报错?虚拟环境和 DeepSeek 一次配到位
开发语言·人工智能·python·agent
octopus_c41 分钟前
C++ 入门
开发语言·c++·算法
步行cgn1 小时前
JSON.stringify 详解:把 JavaScript 对象变成 JSON 字符串
开发语言·javascript·json
香蕉大香蕉(06敬畏市场)1 小时前
高频八股 · JVM(8)
java·jvm·面试·八股·大厂实习
养军博客2 小时前
spirngSecurity 鉴权教程02
java·springsecurity