Library contents

Scala java.lang.Math.addExact

Add integers with an explicit overflow check.

A simple example

java.lang.Math.addExact

  1. Start with 2 and 3
  2. Do this Add the integers
  3. Result 5
The sum fits in the integer type, so the checked addition returns 5.
Lesson.scala
object Lesson extends App {
    println(java.lang.Math.addExact(2, 3))
}
Output
5

Syntax

Scala syntax
java.lang.Math.addExact(stock, shipment)
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 Lesson

Add a shipment to the stock count

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.

From the programval stock = 90
Result102
Lesson.scala

object Lesson {
    def main(args: Array[String]): Unit = {
        val stock = 90
        val shipment = 12
        println(java.lang.Math.addExact(stock, shipment))
    }
}
Output
102

Receiving twelve items increases stock from ninety to 102.

Advertisements

Restock the workshop shelf

A tutor counts 35 components on the shelf. A delivery adds another 18, and the register must show the new total.

Given35 · 18
Worked result53 items

Using 35 · 18 gives 53 items for this measurement.

Combine returned library kits

The morning collection contains 24 kits. Eleven more come back at lunch and the librarian adds the two batches.

Given24 · 11
Worked result35 items

Using 24 · 11 gives 35 items for this measurement.

What to watch for

An out-of-range integer result raises ArithmeticException. Decide how the caller should handle that failure.

Documentation for java.lang.Math.addExact