Ⓜ️Math Class
The Math class contains useful common mathematical methods like square root, trigonometric functions, rounding, etc. It's located in the java.lang package, which contains core Java classes.
Why are all the methods in Math declared as static?
There are a few important reasons:
Mathematics is not an object - mathematical operations don't need an object instance to work. They can be called independently.
Having static methods allows calling Math methods without creating a Math object. We can simply say Math.method() rather than new Math().method().
The implementations of math operations like sine, square root, etc. are optimized and don't depend on object state. They will always work the same way.
Declaring methods static means there is only one copy loaded into memory. This is more efficient than creating Math objects as they are needed.
Mathematics deals with immutable values like integers/doubles. Static methods are well-suited for operating on immutable values.
abs(x)
Returns the absolute value of a number
Math.abs(-5)
max(a,b)
Returns the greater of two numbers
Math.max(5, 10)
min(a,b)
Returns the lesser of two numbers
Math.min(2, 20)
sqrt(a)
Returns the square root of a number
Math.sqrt(64)
pow(a, b)
Returns a raised to the power of b
Math.pow(2, 3)
random()
Returns a random double value between 0-1
Math.random()
round(a)
Rounds a decimal number to the nearest whole number
Math.round(5.3)
ceil(a)
Rounds a number up to the nearest whole number
Math.ceil(5.1)
floor(a)
Rounds a number down to the nearest whole number
Math.floor(6.9)
sin(a)
Returns the sine of an angle in radians
Math.sin(Math.PI/2)
cos(a)
Returns the cosine of an angle in radians
Math.cos(Math.PI)
tan(a)
Returns the tangent of an angle in radians
Math.tan(Math.PI/4)
Last updated