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()

MethodDescriptionExample
round()Rounds to nearest integerMath.round(4.6) → 5
ceil()Always rounds upMath.ceil(4.1) → 5
floor()Always rounds downMath.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:

MethodMeaning
sin()Sine
cos()Cosine
tan()Tangent

Example:



 


⭐ Full Example Using Math Methods



 


📌 Summary Table

FeatureExampleOutput
Max ValueMath.max(10,20)20
Min ValueMath.min(10,20)10
PowerMath.pow(2,3)8
Square RootMath.sqrt(25)5
RandomMath.random()0–1 range
Round UpMath.ceil(4.3)5
Round DownMath.floor(4.9)4

You may also like...