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.

System.out.println(Math.max(10, 20)); // 20
System.out.println(Math.min(10, 20)); // 10

2. Math.sqrt()

Returns the square root.

System.out.println(Math.sqrt(25)); // 5.0

3. Math.abs()

Returns absolute (positive) value.

System.out.println(Math.abs(-10)); // 10

4. Math.pow()

Returns value raised to a power.

System.out.println(Math.pow(2, 3)); // 8.0 (2^3)

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
System.out.println(Math.round(4.6));
System.out.println(Math.ceil(4.1));
System.out.println(Math.floor(4.9));

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:

int randomNum = (int)(Math.random() * 101);
System.out.println(randomNum);

7. Math.PI and Math.E

Constants for mathematical values:

System.out.println(Math.PI); // 3.141592653589793
System.out.println(Math.E); // 2.718281828...

8. Trigonometric Functions

Available methods:

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

Example:

System.out.println(Math.sin(30));

⭐ Full Example Using Math Methods

public class Main {
public static void main(String[] args) {
System.out.println("Max: " + Math.max(10, 20));
System.out.println("Min: " + Math.min(10, 20));
System.out.println("Square Root: " + Math.sqrt(16));
System.out.println("Power: " + Math.pow(2, 5));
System.out.println("Absolute: " + Math.abs(-50));
System.out.println("Rounded: " + Math.round(5.7));
System.out.println("Random (0-100): " + (int)(Math.random() * 101));
}
}

📌 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

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *