How to use Math methods
java
// No import needed — Math is in java.lang
// No object creation needed — all methods are static
double result = Math.sqrt(25); // 5.0
Essential Math methods
Math.abs — Absolute value
java
System.out.println(Math.abs(-15)); // 15
System.out.println(Math.abs(15)); // 15
System.out.println(Math.abs(-3.7)); // 3.7
System.out.println(Math.abs(0)); // 0
java
int a = 10, b = 3;
int distance = Math.abs(a - b); // 7
Math.pow — Exponentiation
java
System.out.println(Math.pow(2, 3)); // 8.0
System.out.println(Math.pow(5, 2)); // 25.0
System.out.println(Math.pow(10, 0)); // 1.0
System.out.println(Math.pow(4, 0.5)); // 2.0 (same as square root)
java
int result = (int) Math.pow(2, 10); // 1024
Math.sqrt — Square root
java
System.out.println(Math.sqrt(25)); // 5.0
System.out.println(Math.sqrt(2)); // 1.4142135623730951
System.out.println(Math.sqrt(0)); // 0.0
Pythagorean theorem example
java
double a = 3, b = 4;
double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
System.out.println("Hypotenuse: " + c); // 5.0
Math.random — Random doubles
java
double r = Math.random(); // e.g., 0.7342...
Generating random integers in a range
java
// Roll a standard die (1-6)
int die = (int)(Math.random() * 6) + 1;
// Random number from 25 to 50
int num = (int)(Math.random() * 26) + 25;
// range = 50 - 25 + 1 = 26
Static methods explained
java
// Static — called on the class
double root = Math.sqrt(9); // Math.method()
// Non-static — called on an object
String s = "hello";
int len = s.length(); // object.method()
Complete example: Distance calculator
java
public class DistanceCalculator {
public static void main(String[] args) {
// Two points on a coordinate plane
double x1 = 1, y1 = 2;
double x2 = 4, y2 = 6;
// Distance formula: sqrt((x2-x1)^2 + (y2-y1)^2)
double distance = Math.sqrt(
Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)
);
System.out.println("Distance: " + distance); // 5.0
// Round to 2 decimal places
double rounded = (int)(distance * 100) / 100.0;
System.out.println("Rounded: " + rounded);
}
}
AP Exam Tips
- •
- •
- •
- •
- •