Java Math

Java Math

Java provides a built-in class called Math in the java.lang package which contains methods for performing mathematical operations like rounding, finding max/min values, square root, powers, random numbers, etc.

You can use Math methods directly without creating an object.


1. Math.max() and Math.min()

Used to find the largest or smallest between two numbers.



 


2. Math.sqrt()

Returns the square root.



 


3. Math.abs()

Returns absolute (positive) value.



 


4. Math.pow()

Returns value raised to a power.



 


5. Math.round(), Math.ceil(), Math.floor()

Method Description Example
round() Rounds to nearest integer Math.round(4.6) → 5
ceil() Always rounds up Math.ceil(4.1) → 5
floor() Always rounds down Math.floor(4.9) → 4


 


6. Math.random()

Generates a random number between 0.0 and 1.0.

System.out.println(Math.random());

Generate random numbers in a range:

➡️ Random number between 0 and 100:



 


7. Math.PI and Math.E

Constants for mathematical values:



 


8. Trigonometric Functions

Available methods:

Method Meaning
sin() Sine
cos() Cosine
tan() Tangent

Example:



 


⭐ Full Example Using Math Methods



 


📌 Summary Table

Feature Example Output
Max Value Math.max(10,20) 20
Min Value Math.min(10,20) 10
Power Math.pow(2,3) 8
Square Root Math.sqrt(25) 5
Random Math.random() 0–1 range
Round Up Math.ceil(4.3) 5
Round Down Math.floor(4.9) 4

You may also like...