Scala java.lang.Math.multiplyExact
Multiply two integer quantities while checking whether the result fits.
A simple example
java.lang.Math.multiplyExact
- Start with 2 and 3
- Do this Multiply
- Result 6
object Lesson extends App {
println(java.lang.Math.multiplyExact(2, 3))
}
6
Syntax
java.lang.Math.multiplyExact(packs, units)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonCount items in a shipment
A delivery reaches the stockroom while the existing count is still on the books. Before recording the new total, the clerk needs arithmetic that can represent the incoming shipment without silently changing the count.
object Lesson {
def main(args: Array[String]): Unit = {
val packs = 12
val units = 24
println(java.lang.Math.multiplyExact(packs, units))
}
}
288
Twelve packs containing 24 items each give 288 items.
Count postcards on a print sheet
A print shop lays out eight rows with six postcards in each row. It calculates how many finished cards a complete sheet produces.
Using 8 · 6 gives 48 items for this measurement.
Order bulbs for display panels
A gallery uses twelve panels that each take fifteen bulbs. The supply desk calculates the number of bulbs for a full installation.
Using 12 · 15 gives 180 items for this measurement.
What to watch for
An out-of-range integer result raises ArithmeticException. Decide how the caller should handle that failure.