📝 What You’ll Learn
- How to use Java’s
Math
class - Common math functions: abs, pow, sqrt, round
- Generating random numbers
- Rounding techniques
➕ Java Math Class
Java provides a utility class Math
in java.lang
that includes methods for performing basic numeric operations.
You don’t need to create an object to use
Math
— all methods are static!
🧠 Common Math Methods
Method | Description |
---|---|
Math.abs(x) |
Absolute value |
Math.pow(a, b) |
a raised to the power b |
Math.sqrt(x) |
Square root |
Math.max(a, b) |
Returns the larger of two values |
Math.min(a, b) |
Returns the smaller of two values |
Math.round(x) |
Rounds to the nearest whole number |
Math.floor(x) |
Rounds down |
Math.ceil(x) |
Rounds up |
Math.random() |
Returns a random number [0.0, 1.0) |
🧪 Examples
System.out.println(Math.abs(-10)); // 10
System.out.println(Math.pow(2, 3)); // 8.0
System.out.println(Math.sqrt(25)); // 5.0
System.out.println(Math.max(10, 20)); // 20
System.out.println(Math.round(3.7)); // 4
System.out.println(Math.floor(3.7)); // 3.0
System.out.println(Math.ceil(3.3)); // 4.0
🎲 Random Numbers
double r = Math.random(); // value between 0.0 and 1.0
System.out.println(r);
To generate a number in a range:
int randomNum = (int)(Math.random() * 10) + 1; // 1 to 10
Or use Random
class:
import java.util.Random;
Random rand = new Random();
int randInt = rand.nextInt(10); // 0 to 9
💡 Trigonometric Methods
Math
also provides trigonometric functions:
Math.sin(angle); // angle in radians
Math.cos(angle);
Math.tan(angle);
To convert degrees to radians:
double radians = Math.toRadians(90);
📘 Recap
- Java’s
Math
class provides tons of utility functions Math.random()
generates pseudo-random numbers- Use
Math.round()
,ceil()
,floor()
for rounding - Trigonometric functions available too