Java Math.max() 與 Math.min()

Math.max() 回傳兩個數值中較大的值,Math.min() 回傳較小的值。

語法

Math.max(int a, int b)
Math.max(long a, long b)
Math.max(float a, float b)
Math.max(double a, double b)

Math.min(int a, int b)
Math.min(long a, long b)
Math.min(float a, float b)
Math.min(double a, double b)

基本用法

// max
System.out.println(Math.max(10, 20));     // 20
System.out.println(Math.max(-5, -10));    // -5
System.out.println(Math.max(3.14, 2.71)); // 3.14

// min
System.out.println(Math.min(10, 20));     // 10
System.out.println(Math.min(-5, -10));    // -10
System.out.println(Math.min(3.14, 2.71)); // 2.71

多個數值比較

// 找出三個數的最大值
int max3 = Math.max(Math.max(10, 20), 15);  // 20

// 找出陣列最大值
int[] arr = {5, 2, 9, 1, 7};
int max = arr[0];
for (int n : arr) {
    max = Math.max(max, n);
}
System.out.println(max);  // 9

// 使用 Stream(Java 8+)
int streamMax = Arrays.stream(arr).max().getAsInt();  // 9
int streamMin = Arrays.stream(arr).min().getAsInt();  // 1

實用範例

限制數值範圍

public static int clamp(int value, int min, int max) {
    return Math.max(min, Math.min(max, value));
}

System.out.println(clamp(5, 0, 10));   // 5(在範圍內)
System.out.println(clamp(-5, 0, 10));  // 0(小於最小值)
System.out.println(clamp(15, 0, 10));  // 10(大於最大值)

// Java 21+ 直接使用 Math.clamp()
// Math.clamp(5, 0, 10);

計算折扣價格

public static double calculatePrice(double price, double discount, double minPrice) {
    double discountedPrice = price * (1 - discount);
    return Math.max(discountedPrice, minPrice);
}

System.out.println(calculatePrice(100, 0.2, 50));  // 80.0
System.out.println(calculatePrice(100, 0.6, 50));  // 50.0(不低於最低價)

特殊值處理

// NaN 處理
System.out.println(Math.max(Double.NaN, 5));  // NaN
System.out.println(Math.min(Double.NaN, 5));  // NaN

// 正負零
System.out.println(Math.max(0.0, -0.0));  // 0.0
System.out.println(Math.min(0.0, -0.0));  // -0.0

重點整理

  • Math.max() 回傳較大值,Math.min() 回傳較小值
  • 支援 intlongfloatdouble
  • 多個數值比較可巢狀使用或用 Stream
  • 常用於數值範圍限制(clamp)