Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Math.multiplyExact() ใน Java: คูณกับ Overflow Detection

Math.multiplyExact()

เมธอด Math.multiplyExact() (Java 8+) คูณสองค่าและ โยน ArithmeticException หากล้น (Overflow) แทนที่จะ silent wrap-around

ตัวอย่างโค้ด

import java.lang.Math; 

public class Demo { 
    public static void main(String args[]) { 
        int a = 12, b = 34; 
        System.out.println("int: " + a + " × " + b + " = " + Math.multiplyExact(a, b)); 
        
        long c = 78, d = 93; 
        System.out.println("long: " + c + " × " + d + " = " + Math.multiplyExact(c, d)); 
        
        // ทดสอบ Overflow
        try { 
            int max = Integer.MAX_VALUE; 
            System.out.println("MAX_VALUE × 2 = " + Math.multiplyExact(max, 2)); 
        } catch (ArithmeticException e) { 
            System.out.println("Overflow! " + e.getMessage()); 
        } 
    } 
}

ผลลัพธ์

int: 12 × 34 = 408
long: 78 × 93 = 7254
Overflow! integer overflow

คำอธิบาย

ปกติ Java silent overflow สำหรับ int/long:

int x = Integer.MAX_VALUE; 
System.out.println(x + 1); // -2147483648 (wrap around - ไม่มี error!)

multiplyExact ตรวจสอบ overflow และโยน ArithmeticException ทันที

Overloads

Signatureคำอธิบาย
int multiplyExact(int a, int b)คูณ int, return int
long multiplyExact(long a, long b)คูณ long, return long
int multiplyExact(int a, int b, int c)Java 9+: คูณ 3 ตัว (int)
long multiplyExact(long a, long b, long c)Java 9+: คูณ 3 ตัว (long)

Related Exact Methods

Math.addExact(a, b)       // บวกกับ overflow check
Math.subtractExact(a, b)  // ลบกับ overflow check
Math.incrementExact(a)    // a + 1
Math.decrementExact(a)    // a - 1
Math.negateExact(a)       // -a (เช็ค MIN_VALUE)
Math.toIntExact(long)     // long -> int with check

เมื่อไหร่ควรใช้

  • Financial calculations (เงิน ไม่ยอมให้ผิด)
  • Array indexing calculations
  • Cryptographic computations
  • ใดๆ ที่ overflow เป็น bug ร้ายแรง

Performance

  • ช้ากว่าการคูณปกติเล็กน้อย (มี branch check)
  • แต่เร็วกว่าการเช็คเองด้วย if
  • JIT อาจ optimize ได้ในบางกรณี

BigInteger Alternative

// ไม่มี overflow (arbitrary precision)
BigInteger a = BigInteger.valueOf(Integer.MAX_VALUE); 
BigInteger result = a.multiply(BigInteger.valueOf(2)); 
// result = 4294967294 (ถูกต้อง)