Java Maths

In Java, the "java.lang.Math" class is a part of the standard library and provides a set of static methods for performing various mathematical operations. Here are some of the commonly used functions in the Math library in Java:

Basic Arithmetic Functions

FunctionCodeDescription
Math.abs(x)int absoluteValue = Math.abs(-5);Returns the absolute value of x.
Math.addExact(int x, int y)int result = Math.addExact(x, y);Adds two integers or long values, throwing an exception if the result overflows.

Exponentiation and Logarithmic Functions

FunctionCodeDescription
Math.pow(x, y)double powerResult = Math.pow(2, 3);Returns x raised to the power of y.
Math.exp(x)double exponentialResult = Math.exp(1);Returns the exponential value of x.
Math.log(x)double logResult = Math.log(10);Returns the natural logarithm (base e) of x.
Math.log10(x)double log10Result = Math.log10(100);Returns the base 10 logarithm of x.

Trigonometric Functions

FunctionCodeDescription
Math.sin(x)double sine = Math.sin(Math.PI / 2);Calculates sin of a number.
Math.cos(x)double cosine = Math.cos(Math.PI);Calculates cos of a number.
Math.tan(x)double tangent = Math.tan(Math.PI / 4);Calculates tan of a number.

Floor Functions

FunctionCodeDescription
Math.round(x)double roundedValue = Math.round(3.75);Rounds x to the nearest integer.
Math.ceil(x)double ceilingValue = Math.ceil(4.2);Returns the smallest integer greater than or equal to x.
Math.floor(x)double floorValue = Math.floor(4.7);Returns the largest integer less than or equal to x.

Random Number Generation

FunctionCodeDescription
Math.random() double randomValue = Math.random();Returns a random double value between 0.0 (inclusive) and 1.0 (exclusive).

Min and Max Functions

FunctionCodeDescription
Math.min(a, b)int min = Math.min(10, 15);Returns the smaller of two values a and b.
Math.max(a, b)int max = Math.max(30, 20);Returns the maximum of two values a and b.

Square Root and Exponents

FunctionCodeDescription
Math.sqrt(x)double squareRoot = Math.sqrt(25);Returns the square root of x.
Math.cbrt(x)double cubeRoot = Math.cbrt(8);Returns the cube root of x.

Conversion Functions

FunctionCodeDescription
Math.toDegrees(x)double degrees = Math.toDegrees(Math.PI / 2);Converts an angle measured in radians to degrees.
Math.toRadians(x)double radians = Math.toRadians(90);Converts an angle measured in degrees to radians.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min