Search code examples
javaandroidutility

Android version compatibility for Math.toIntExact Utility method


The Math.toIntExact method is throwing an exception on my Android 6.0 emulator. (More recent emulator versions are ok)

This Microsoft doc is the only doc I found about it. Am I correct in thinking that Math.toIntExact is not compatible before Android 9.0 ?

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.dmurphy.remotescrumpoker, PID: 9527
    java.lang.NoSuchMethodError: No static method toIntExact(J)I in class Ljava/lang/Math; or its super classes (declaration of 'java.lang.Math' appears in /system/framework/core-libart.jar)
        at com.dmurphy.remotescrumpoker.Activity_TeamDetails$6.onComplete(Activity_TeamDetails.java:268)
        at com.google.android.gms.tasks.zzj.run(Unknown Source)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
D/FA: Event not sent since app measurement is disabled

Solution

  • Math::toIntExact, as per the documentation, has been introduced with API level 24, that is Android 7.0. So yeah, it's not available on Android 6.

    The good news is that you can easily implement it yourself by extracting it from the java.lang.Math source code.

    public static int toIntExact(long value) {
        if ((int)value != value) {
            throw new ArithmeticException("integer overflow");
        }
        return (int)value;
    }