Java Math
Performing mathematical operations in Java
🔢 What is Java Math?
Java Math provides built-in mathematical functions and operations. You can perform calculations, use mathematical constants, and apply complex mathematical operations easily in your Java programs.
// Simple math operations in Java
int sum = 5 + 3; // Addition
int product = 4 * 6; // Multiplication
double result = Math.sqrt(16); // Square root
System.out.println("Sum: " + sum);
Output:
Sum: 8
Basic Math Operations
Addition
Add numbers together
int result = 10 + 5; // 15
Subtraction
Subtract one number from another
int result = 10 - 3; // 7
Multiplication
Multiply numbers
int result = 4 * 5; // 20
Division
Divide one number by another
double result = 15.0 / 3; // 5.0
🔹 Math Class Methods
Java provides the Math class with useful mathematical functions:
public class MathExample {
public static void main(String[] args) {
// Maximum and minimum
int max = Math.max(10, 20); // 20
int min = Math.min(10, 20); // 10
// Power and square root
double power = Math.pow(2, 3); // 8.0 (2^3)
double sqrt = Math.sqrt(25); // 5.0
// Absolute value
int abs = Math.abs(-15); // 15
System.out.println("Max: " + max);
System.out.println("Square root: " + sqrt);
}
}
Output:
Max: 20
Square root: 5.0
🔹 Random Numbers
Generate random numbers using Math.random():
public class RandomExample {
public static void main(String[] args) {
// Random number between 0.0 and 1.0
double random = Math.random();
// Random integer between 1 and 10
int randomInt = (int)(Math.random() * 10) + 1;
System.out.println("Random number: " + random);
System.out.println("Random 1-10: " + randomInt);
}
}
Output:
Random number: 0.7234567890123456
Random 1-10: 7