Java

public class Program {
public static void main(String[] args) {
*// Get these known constants.*
double value1 = **Math.E**;
double value2 = **Math.PI**;
System.out.println(value1);
System.out.println(value2);
}
}2.718281828459045
3.141592653589793

import java.lang.Math;
public class Program {
public static void main(String[] args) {
*// Part 1: use exact methods.*
int result1 = **Math.addExact**(1, 1);
int result2 = Math.addExact(100, 1);
int result3 = Math.subtractExact(100, 1);
int result4 = Math.multiplyExact(5, 4);
int result5 = Math.incrementExact(2);
int result6 = Math.decrementExact(1000);
int result7 = Math.negateExact(100);
*// Part 2: display our results.*
System.out.println(result1 + *" "* + result2 + *" "* + result3 + *" "*
+ result4 + *" "* + result5 + *" "* + result6 + *" "* + result7);
*// Part 3: an ArithmeticException is thrown if a number overflows.*
try {
int invalid = Math.multiplyExact(Integer.MAX_VALUE, 100);
} catch (Exception ex) {
System.out.println(ex);
}
}
}2 101 99 20 3 999 -100
java.lang.ArithmeticException: integer overflow

import java.lang.Math;
public class Program {
public static void main(String[] args) {
*// An int can store the value 100.*
long test = 100;
int result = Math.**toIntExact**(test);
System.out.println(*"INT: "* + result);
*// This will cause an exception, as the int cannot store the value.*
test = Long.MAX_VALUE;
result = Math.**toIntExact**(test);
}
}INT: 100
Exception in thread "main" java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.toIntExact(Math.java:1071)
at Program.main(Program.java:13)

Math.abs

Math.floor

Math.ceil

sqrt

Math.max

Math.pow

Random

Compound Interest

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Jun 9, 2022 (simplify).