Java Math Class - Complete Guide
Java Math Class
The Math class in Java provides methods for performing basic mathematical operations such as absolute value, square root, trigonometry, rounding, and more.
What is the Math Class?
The Math class is part of the java.lang package and provides static methods for mathematical calculations.
1public class MathIntro {
2 public static void main(String[] args) {
3 // No need to create Math object - all methods are static
4 double result = Math.sqrt(16); // Direct access
5 System.out.println("Square root of 16: " + result); // 4.0
6
7 // No import needed - java.lang is imported automatically
8 double power = Math.pow(2, 3); // 2^3 = 8
9 System.out.println("2 to the power 3: " + power); // 8.0
10 }
11}Key Points:
- ›All methods are static - call directly without creating object
- ›Located in
java.langpackage - no import needed - ›All methods are final - cannot be overridden
- ›The class itself is final - cannot be extended
Mathematical Constants
PI and E
1public class MathConstants {
2 public static void main(String[] args) {
3 // PI - Ratio of circumference to diameter
4 System.out.println("PI: " + Math.PI);
5 // Output: 3.141592653589793
6
7 // E - Base of natural logarithms
8 System.out.println("E: " + Math.E);
9 // Output: 2.718281828459045
10
11 // Using constants in calculations
12 double radius = 5.0;
13 double circumference = 2 * Math.PI * radius;
14 double area = Math.PI * radius * radius;
15
16 System.out.println("Radius: " + radius);
17 System.out.println("Circumference: " + circumference); // 31.41...
18 System.out.println("Area: " + area); // 78.53...
19
20 // Circle calculations
21 System.out.println("\n--- Circle Calculations ---");
22 printCircleInfo(3.0);
23 printCircleInfo(7.5);
24 }
25
26 static void printCircleInfo(double radius) {
27 double circumference = 2 * Math.PI * radius;
28 double area = Math.PI * Math.pow(radius, 2);
29
30 System.out.printf("Radius: %.1f\n", radius);
31 System.out.printf("Circumference: %.2f\n", circumference);
32 System.out.printf("Area: %.2f\n\n", area);
33 }
34}Output:
PI: 3.141592653589793
E: 2.718281828459045
Radius: 5.0
Circumference: 31.41592653589793
Area: 78.53981633974483
--- Circle Calculations ---
Radius: 3.0
Circumference: 18.85
Area: 28.27
Radius: 7.5
Circumference: 47.12
Area: 176.71
Basic Arithmetic Methods
1. abs() - Absolute Value
Returns the absolute (positive) value of a number.
1public class AbsoluteValue {
2 public static void main(String[] args) {
3 // Integer absolute value
4 System.out.println("abs(-10): " + Math.abs(-10)); // 10
5 System.out.println("abs(10): " + Math.abs(10)); // 10
6 System.out.println("abs(0): " + Math.abs(0)); // 0
7
8 // Double absolute value
9 System.out.println("abs(-15.7): " + Math.abs(-15.7)); // 15.7
10 System.out.println("abs(15.7): " + Math.abs(15.7)); // 15.7
11
12 // Long absolute value
13 long bigNum = -9876543210L;
14 System.out.println("abs(" + bigNum + "): " + Math.abs(bigNum));
15 // Output: 9876543210
16
17 // Practical example: Calculate distance
18 int temperature1 = 75;
19 int temperature2 = 45;
20 int difference = Math.abs(temperature1 - temperature2);
21 System.out.println("Temperature difference: " + difference + "°F");
22 // Output: 30°F
23
24 // Calculate price difference
25 double price1 = 49.99;
26 double price2 = 59.99;
27 double priceDiff = Math.abs(price1 - price2);
28 System.out.println("Price difference: $" + priceDiff);
29 // Output: $10.0
30 }
31}Use Cases:
- ›Finding distance between two points
- ›Calculating differences (temperature, price, etc.)
- ›Ensuring positive values
- ›Error margins
2. max() and min() - Maximum and Minimum
Returns the larger or smaller of two values.
1public class MaxMin {
2 public static void main(String[] args) {
3 // Integer max/min
4 System.out.println("max(10, 20): " + Math.max(10, 20)); // 20
5 System.out.println("min(10, 20): " + Math.min(10, 20)); // 10
6
7 // Double max/min
8 System.out.println("max(15.5, 15.8): " + Math.max(15.5, 15.8)); // 15.8
9 System.out.println("min(15.5, 15.8): " + Math.min(15.5, 15.8)); // 15.5
10
11 // Negative numbers
12 System.out.println("max(-5, -10): " + Math.max(-5, -10)); // -5
13 System.out.println("min(-5, -10): " + Math.min(-5, -10)); // -10
14
15 // Finding max of multiple numbers
16 int a = 45, b = 23, c = 67, d = 12;
17 int max = Math.max(Math.max(a, b), Math.max(c, d));
18 System.out.println("Max of 45, 23, 67, 12: " + max); // 67
19
20 // Practical: Temperature limits
21 double currentTemp = 78.5;
22 double maxTemp = 75.0;
23 double minTemp = 65.0;
24
25 double adjustedTemp = Math.min(currentTemp, maxTemp);
26 adjustedTemp = Math.max(adjustedTemp, minTemp);
27
28 System.out.println("Current: " + currentTemp);
29 System.out.println("Adjusted (within 65-75): " + adjustedTemp);
30 // Output: 75.0 (capped at max)
31
32 // Finding range
33 int[] scores = {85, 92, 78, 95, 88};
34 int maxScore = scores[0];
35 int minScore = scores[0];
36
37 for (int score : scores) {
38 maxScore = Math.max(maxScore, score);
39 minScore = Math.min(minScore, score);
40 }
41
42 System.out.println("Highest score: " + maxScore); // 95
43 System.out.println("Lowest score: " + minScore); // 78
44 System.out.println("Range: " + (maxScore - minScore)); // 17
45 }
46}Use Cases:
- ›Clamping values to a range
- ›Finding extremes in data
- ›Boundary checking
- ›Temperature/value limits
3. pow() - Power
Raises a number to the power of another number.
1public class PowerExample {
2 public static void main(String[] args) {
3 // Basic powers
4 System.out.println("2^3: " + Math.pow(2, 3)); // 8.0
5 System.out.println("5^2: " + Math.pow(5, 2)); // 25.0
6 System.out.println("10^3: " + Math.pow(10, 3)); // 1000.0
7
8 // Fractional powers (roots)
9 System.out.println("16^0.5: " + Math.pow(16, 0.5)); // 4.0 (square root)
10 System.out.println("8^(1/3): " + Math.pow(8, 1.0/3)); // 2.0 (cube root)
11
12 // Negative powers (reciprocals)
13 System.out.println("2^-1: " + Math.pow(2, -1)); // 0.5 (1/2)
14 System.out.println("10^-2: " + Math.pow(10, -2)); // 0.01 (1/100)
15
16 // Zero power
17 System.out.println("5^0: " + Math.pow(5, 0)); // 1.0 (anything^0 = 1)
18
19 // Practical: Compound interest
20 double principal = 1000.0;
21 double rate = 0.05; // 5% annual
22 int years = 10;
23
24 double amount = principal * Math.pow(1 + rate, years);
25 System.out.printf("Investment after %d years: $%.2f\n", years, amount);
26 // Output: $1628.89
27
28 // Area of square
29 double side = 7.5;
30 double area = Math.pow(side, 2);
31 System.out.println("Area of square (side " + side + "): " + area);
32 // Output: 56.25
33
34 // Volume of cube
35 double cubeArea = Math.pow(side, 3);
36 System.out.println("Volume of cube (side " + side + "): " + cubeArea);
37 // Output: 421.875
38
39 // Exponential growth
40 int initialBacteria = 100;
41 int doublingTimes = 5;
42 int finalBacteria = (int)(initialBacteria * Math.pow(2, doublingTimes));
43 System.out.println("Bacteria after " + doublingTimes + " doublings: " + finalBacteria);
44 // Output: 3200
45 }
46}Use Cases:
- ›Calculating compound interest
- ›Area and volume formulas
- ›Exponential growth/decay
- ›Scientific calculations
4. sqrt() - Square Root
Returns the square root of a number.
1public class SquareRoot {
2 public static void main(String[] args) {
3 // Basic square roots
4 System.out.println("sqrt(16): " + Math.sqrt(16)); // 4.0
5 System.out.println("sqrt(25): " + Math.sqrt(25)); // 5.0
6 System.out.println("sqrt(2): " + Math.sqrt(2)); // 1.414...
7
8 // Non-perfect squares
9 System.out.println("sqrt(10): " + Math.sqrt(10)); // 3.162...
10 System.out.println("sqrt(50): " + Math.sqrt(50)); // 7.071...
11
12 // Zero and one
13 System.out.println("sqrt(0): " + Math.sqrt(0)); // 0.0
14 System.out.println("sqrt(1): " + Math.sqrt(1)); // 1.0
15
16 // Negative number (returns NaN - Not a Number)
17 System.out.println("sqrt(-4): " + Math.sqrt(-4)); // NaN
18
19 // Practical: Pythagorean theorem (a² + b² = c²)
20 double a = 3.0;
21 double b = 4.0;
22 double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
23 System.out.printf("Hypotenuse of triangle (%.1f, %.1f): %.1f\n", a, b, c);
24 // Output: 5.0
25
26 // Distance between two points
27 int x1 = 2, y1 = 3;
28 int x2 = 5, y2 = 7;
29 double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
30 System.out.printf("Distance between (%d,%d) and (%d,%d): %.2f\n",
31 x1, y1, x2, y2, distance);
32 // Output: 5.00
33
34 // Standard deviation (simplified)
35 int[] values = {10, 12, 14, 16, 18};
36 double mean = 14.0;
37 double sumSquaredDiff = 0;
38
39 for (int value : values) {
40 sumSquaredDiff += Math.pow(value - mean, 2);
41 }
42
43 double variance = sumSquaredDiff / values.length;
44 double stdDev = Math.sqrt(variance);
45
46 System.out.printf("Standard deviation: %.2f\n", stdDev);
47 // Output: 2.83
48 }
49}Use Cases:
- ›Pythagorean theorem
- ›Distance calculations
- ›Standard deviation
- ›Geometric formulas
5. cbrt() - Cube Root
Returns the cube root of a number.
1public class CubeRoot {
2 public static void main(String[] args) {
3 // Basic cube roots
4 System.out.println("cbrt(8): " + Math.cbrt(8)); // 2.0
5 System.out.println("cbrt(27): " + Math.cbrt(27)); // 3.0
6 System.out.println("cbrt(64): " + Math.cbrt(64)); // 4.0
7
8 // Non-perfect cubes
9 System.out.println("cbrt(10): " + Math.cbrt(10)); // 2.154...
10 System.out.println("cbrt(100): " + Math.cbrt(100)); // 4.641...
11
12 // Negative numbers (cube root of negative exists)
13 System.out.println("cbrt(-8): " + Math.cbrt(-8)); // -2.0
14 System.out.println("cbrt(-27): " + Math.cbrt(-27)); // -3.0
15
16 // Finding side of cube given volume
17 double volume = 125.0;
18 double side = Math.cbrt(volume);
19 System.out.println("Cube with volume " + volume + " has side: " + side);
20 // Output: 5.0
21
22 // Comparing sqrt and cbrt
23 double num = 64;
24 System.out.println("sqrt(64): " + Math.sqrt(num)); // 8.0
25 System.out.println("cbrt(64): " + Math.cbrt(num)); // 4.0
26 }
27}Rounding Methods
1. round() - Round to Nearest Integer
Rounds to the nearest whole number. .5 rounds up.
1public class RoundExample {
2 public static void main(String[] args) {
3 // Basic rounding
4 System.out.println("round(3.2): " + Math.round(3.2)); // 3
5 System.out.println("round(3.5): " + Math.round(3.5)); // 4
6 System.out.println("round(3.7): " + Math.round(3.7)); // 4
7
8 // Negative numbers
9 System.out.println("round(-3.2): " + Math.round(-3.2)); // -3
10 System.out.println("round(-3.5): " + Math.round(-3.5)); // -3 (rounds toward positive)
11 System.out.println("round(-3.7): " + Math.round(-3.7)); // -4
12
13 // Edge cases
14 System.out.println("round(0.5): " + Math.round(0.5)); // 1
15 System.out.println("round(-0.5): " + Math.round(-0.5)); // 0
16
17 // Double vs Float
18 double d = 3.7;
19 float f = 3.7f;
20 System.out.println("round(double 3.7): " + Math.round(d)); // returns long: 4
21 System.out.println("round(float 3.7): " + Math.round(f)); // returns int: 4
22
23 // Practical: Rounding prices
24 double price = 19.99;
25 double tax = price * 0.08;
26 double total = price + tax;
27
28 System.out.println("Price: $" + price);
29 System.out.println("Tax: $" + tax);
30 System.out.println("Total (raw): $" + total);
31 System.out.println("Total (rounded cents): $" + Math.round(total * 100.0) / 100.0);
32
33 // Rounding to specific decimal places
34 double value = 3.14159;
35 double rounded1 = Math.round(value * 10.0) / 10.0; // 1 decimal
36 double rounded2 = Math.round(value * 100.0) / 100.0; // 2 decimals
37 double rounded3 = Math.round(value * 1000.0) / 1000.0; // 3 decimals
38
39 System.out.println("Original: " + value);
40 System.out.println("1 decimal: " + rounded1); // 3.1
41 System.out.println("2 decimals: " + rounded2); // 3.14
42 System.out.println("3 decimals: " + rounded3); // 3.142
43 }
44}2. ceil() - Round Up
Always rounds up to the next integer.
1public class CeilExample {
2 public static void main(String[] args) {
3 // Basic ceiling
4 System.out.println("ceil(3.1): " + Math.ceil(3.1)); // 4.0
5 System.out.println("ceil(3.5): " + Math.ceil(3.5)); // 4.0
6 System.out.println("ceil(3.9): " + Math.ceil(3.9)); // 4.0
7
8 // Already integer
9 System.out.println("ceil(3.0): " + Math.ceil(3.0)); // 3.0
10
11 // Negative numbers (rounds toward positive infinity)
12 System.out.println("ceil(-3.1): " + Math.ceil(-3.1)); // -3.0
13 System.out.println("ceil(-3.9): " + Math.ceil(-3.9)); // -3.0
14
15 // Zero
16 System.out.println("ceil(0.1): " + Math.ceil(0.1)); // 1.0
17 System.out.println("ceil(-0.1): " + Math.ceil(-0.1)); // 0.0
18
19 // Practical: Calculate pages needed
20 int totalItems = 47;
21 int itemsPerPage = 10;
22 int pagesNeeded = (int)Math.ceil((double)totalItems / itemsPerPage);
23 System.out.println("Items: " + totalItems);
24 System.out.println("Per page: " + itemsPerPage);
25 System.out.println("Pages needed: " + pagesNeeded); // 5
26
27 // Boxes needed for shipping
28 int products = 23;
29 int productsPerBox = 6;
30 int boxesNeeded = (int)Math.ceil((double)products / productsPerBox);
31 System.out.println("\nProducts: " + products);
32 System.out.println("Per box: " + productsPerBox);
33 System.out.println("Boxes needed: " + boxesNeeded); // 4
34
35 // Minimum price
36 double costPerUnit = 2.35;
37 int units = 7;
38 double totalCost = costPerUnit * units;
39 double roundedUp = Math.ceil(totalCost);
40
41 System.out.println("\nTotal cost: $" + totalCost); // $16.45
42 System.out.println("Rounded up: $" + roundedUp); // $17.0
43 }
44}Use Cases:
- ›Calculating pages/boxes needed
- ›Ensuring minimum quantities
- ›Rounding up prices
- ›Pagination
3. floor() - Round Down
Always rounds down to the previous integer.
1public class FloorExample {
2 public static void main(String[] args) {
3 // Basic floor
4 System.out.println("floor(3.1): " + Math.floor(3.1)); // 3.0
5 System.out.println("floor(3.5): " + Math.floor(3.5)); // 3.0
6 System.out.println("floor(3.9): " + Math.floor(3.9)); // 3.0
7
8 // Already integer
9 System.out.println("floor(3.0): " + Math.floor(3.0)); // 3.0
10
11 // Negative numbers (rounds toward negative infinity)
12 System.out.println("floor(-3.1): " + Math.floor(-3.1)); // -4.0
13 System.out.println("floor(-3.9): " + Math.floor(-3.9)); // -4.0
14
15 // Practical: Integer division alternative
16 double a = 17.0;
17 double b = 5.0;
18 double result = Math.floor(a / b);
19 System.out.println("17 / 5 (floored): " + result); // 3.0
20
21 // Complete sets
22 int totalStudents = 27;
23 int studentsPerTeam = 4;
24 int completeTeams = (int)Math.floor((double)totalStudents / studentsPerTeam);
25 int leftover = totalStudents % studentsPerTeam;
26
27 System.out.println("Students: " + totalStudents);
28 System.out.println("Per team: " + studentsPerTeam);
29 System.out.println("Complete teams: " + completeTeams); // 6
30 System.out.println("Students left: " + leftover); // 3
31
32 // Discount calculation (round down)
33 double price = 49.99;
34 double discountPercent = 0.15;
35 double discount = Math.floor(price * discountPercent * 100) / 100;
36
37 System.out.println("\nPrice: $" + price);
38 System.out.println("Discount: $" + discount); // $7.49 (not $7.4985)
39 }
40}Use Cases:
- ›Integer division
- ›Complete groups/sets
- ›Discounts (round down)
- ›Truncating decimals
Comparison: round vs ceil vs floor
1public class RoundingComparison {
2 public static void main(String[] args) {
3 double[] values = {3.1, 3.5, 3.9, -3.1, -3.5, -3.9};
4
5 System.out.println("Value\tround\tceil\tfloor");
6 System.out.println("-----\t-----\t----\t-----");
7
8 for (double value : values) {
9 System.out.printf("%.1f\t%d\t%.0f\t%.0f\n",
10 value,
11 Math.round(value),
12 Math.ceil(value),
13 Math.floor(value)
14 );
15 }
16 }
17}Output:
Value round ceil floor
----- ----- ---- -----
3.1 3 4 3
3.5 4 4 3
3.9 4 4 3
-3.1 -3 -3 -4
-3.5 -3 -3 -4
-3.9 -4 -3 -4
Trigonometric Functions
Basic Trigonometry
1public class TrigExample {
2 public static void main(String[] args) {
3 // Angles in RADIANS (not degrees!)
4 double angleRadians = Math.PI / 4; // 45 degrees
5
6 System.out.println("Angle: " + Math.toDegrees(angleRadians) + "°");
7 System.out.println("sin(45°): " + Math.sin(angleRadians)); // 0.707...
8 System.out.println("cos(45°): " + Math.cos(angleRadians)); // 0.707...
9 System.out.println("tan(45°): " + Math.tan(angleRadians)); // 1.0
10
11 // Convert degrees to radians
12 double degrees = 90;
13 double radians = Math.toRadians(degrees);
14
15 System.out.println("\nAngle: " + degrees + "°");
16 System.out.println("sin(90°): " + Math.sin(radians)); // 1.0
17 System.out.println("cos(90°): " + Math.cos(radians)); // ~0.0
18 System.out.println("tan(90°): " + Math.tan(radians)); // Very large number
19
20 // Common angles
21 System.out.println("\n--- Common Angles ---");
22 printTrigValues(0);
23 printTrigValues(30);
24 printTrigValues(45);
25 printTrigValues(60);
26 printTrigValues(90);
27
28 // Inverse trig functions
29 System.out.println("\n--- Inverse Functions ---");
30 double ratio = 0.5;
31 double asinResult = Math.asin(ratio); // Returns radians
32 double acosResult = Math.acos(ratio);
33 double atanResult = Math.atan(ratio);
34
35 System.out.println("asin(0.5) = " + Math.toDegrees(asinResult) + "°"); // 30°
36 System.out.println("acos(0.5) = " + Math.toDegrees(acosResult) + "°"); // 60°
37 System.out.println("atan(0.5) = " + Math.toDegrees(atanResult) + "°"); // 26.56°
38
39 // Practical: Calculate height of building
40 double distance = 50; // meters from building
41 double angleDegrees = 60; // looking up at 60°
42 double height = distance * Math.tan(Math.toRadians(angleDegrees));
43
44 System.out.printf("\nBuilding height: %.2f meters\n", height); // 86.60m
45 }
46
47 static void printTrigValues(double degrees) {
48 double radians = Math.toRadians(degrees);
49 System.out.printf("%.0f°: sin=%.3f, cos=%.3f, tan=%.3f\n",
50 degrees,
51 Math.sin(radians),
52 Math.cos(radians),
53 Math.tan(radians)
54 );
55 }
56}Output:
--- Common Angles ---
0°: sin=0.000, cos=1.000, tan=0.000
30°: sin=0.500, cos=0.866, tan=0.577
45°: sin=0.707, cos=0.707, tan=1.000
60°: sin=0.866, cos=0.500, tan=1.732
90°: sin=1.000, cos=0.000, tan=16331239353195370.000
Important:
- ›Java trig functions use radians, not degrees
- ›Use
Math.toRadians()to convert degrees → radians - ›Use
Math.toDegrees()to convert radians → degrees
Random Numbers
random() - Generate Random Numbers
Returns a random double between 0.0 (inclusive) and 1.0 (exclusive).
1public class RandomExample {
2 public static void main(String[] args) {
3 // Basic random (0.0 to 1.0)
4 System.out.println("Random: " + Math.random()); // e.g., 0.731...
5 System.out.println("Random: " + Math.random()); // e.g., 0.245...
6 System.out.println("Random: " + Math.random()); // e.g., 0.892...
7
8 // Random integer from 0 to 9
9 int random0to9 = (int)(Math.random() * 10);
10 System.out.println("Random 0-9: " + random0to9);
11
12 // Random integer from 1 to 10
13 int random1to10 = (int)(Math.random() * 10) + 1;
14 System.out.println("Random 1-10: " + random1to10);
15
16 // Random integer from 1 to 100
17 int random1to100 = (int)(Math.random() * 100) + 1;
18 System.out.println("Random 1-100: " + random1to100);
19
20 // Random in specific range: min to max
21 int min = 50;
22 int max = 100;
23 int randomInRange = (int)(Math.random() * (max - min + 1)) + min;
24 System.out.println("Random 50-100: " + randomInRange);
25
26 // Dice roll (1-6)
27 int dice = (int)(Math.random() * 6) + 1;
28 System.out.println("Dice roll: " + dice);
29
30 // Coin flip
31 String coinFlip = Math.random() < 0.5 ? "Heads" : "Tails";
32 System.out.println("Coin flip: " + coinFlip);
33
34 // Random color
35 String[] colors = {"Red", "Blue", "Green", "Yellow", "Purple"};
36 int randomIndex = (int)(Math.random() * colors.length);
37 System.out.println("Random color: " + colors[randomIndex]);
38
39 // Multiple random numbers
40 System.out.println("\n5 random dice rolls:");
41 for (int i = 0; i < 5; i++) {
42 int roll = (int)(Math.random() * 6) + 1;
43 System.out.println("Roll " + (i + 1) + ": " + roll);
44 }
45
46 // Random double in range
47 double minTemp = 65.0;
48 double maxTemp = 75.0;
49 double randomTemp = Math.random() * (maxTemp - minTemp) + minTemp;
50 System.out.printf("\nRandom temperature: %.2f°F\n", randomTemp);
51
52 // Random boolean
53 boolean randomBoolean = Math.random() < 0.5;
54 System.out.println("Random boolean: " + randomBoolean);
55 }
56}Formula for Random Range:
1// Random integer from min to max (inclusive)
2int random = (int)(Math.random() * (max - min + 1)) + min;
3
4// Random double from min to max
5double random = Math.random() * (max - min) + min;Other Useful Methods
1. signum() - Sign of Number
Returns -1, 0, or 1 indicating the sign.
1public class SignumExample {
2 public static void main(String[] args) {
3 System.out.println("signum(10): " + Math.signum(10)); // 1.0
4 System.out.println("signum(-10): " + Math.signum(-10)); // -1.0
5 System.out.println("signum(0): " + Math.signum(0)); // 0.0
6
7 // Practical: Determine direction
8 int score = 5;
9 int previousScore = 8;
10 int change = score - previousScore;
11
12 String direction;
13 if (Math.signum(change) > 0) {
14 direction = "Increased";
15 } else if (Math.signum(change) < 0) {
16 direction = "Decreased";
17 } else {
18 direction = "No change";
19 }
20
21 System.out.println("Score " + direction + " by " + Math.abs(change));
22 // Output: Score Decreased by 3
23 }
24}2. log() and log10() - Logarithms
1public class LogExample {
2 public static void main(String[] args) {
3 // Natural log (base e)
4 System.out.println("log(1): " + Math.log(1)); // 0.0
5 System.out.println("log(e): " + Math.log(Math.E)); // 1.0
6 System.out.println("log(10): " + Math.log(10)); // 2.302...
7
8 // Log base 10
9 System.out.println("log10(1): " + Math.log10(1)); // 0.0
10 System.out.println("log10(10): " + Math.log10(10)); // 1.0
11 System.out.println("log10(100): " + Math.log10(100)); // 2.0
12 System.out.println("log10(1000): " + Math.log10(1000)); // 3.0
13
14 // Practical: Number of digits
15 int number = 12345;
16 int digits = (int)Math.log10(number) + 1;
17 System.out.println("Number " + number + " has " + digits + " digits");
18 // Output: 5
19 }
20}3. exp() - Exponential (e^x)
1public class ExpExample {
2 public static void main(String[] args) {
3 // e raised to power
4 System.out.println("exp(0): " + Math.exp(0)); // 1.0
5 System.out.println("exp(1): " + Math.exp(1)); // 2.718... (e)
6 System.out.println("exp(2): " + Math.exp(2)); // 7.389...
7
8 // Exponential growth
9 double growthRate = 0.05; // 5%
10 double time = 10;
11 double factor = Math.exp(growthRate * time);
12
13 System.out.printf("Growth factor after %.0f years: %.3f\n", time, factor);
14 // Output: 1.649 (64.9% growth)
15 }
16}Practical Applications
1. Calculate Distance Between Points
1public class DistanceCalculator {
2 public static void main(String[] args) {
3 // 2D distance
4 double distance2D = calculateDistance2D(0, 0, 3, 4);
5 System.out.println("2D Distance: " + distance2D); // 5.0
6
7 // 3D distance
8 double distance3D = calculateDistance3D(1, 2, 3, 4, 5, 6);
9 System.out.printf("3D Distance: %.2f\n", distance3D); // 5.20
10
11 // Real example: City distances
12 double newYork_x = 40.7128, newYork_y = -74.0060;
13 double boston_x = 42.3601, boston_y = -71.0589;
14
15 double dist = calculateDistance2D(newYork_x, newYork_y, boston_x, boston_y);
16 System.out.printf("Approximate distance: %.2f degrees\n", dist);
17 }
18
19 static double calculateDistance2D(double x1, double y1, double x2, double y2) {
20 return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
21 }
22
23 static double calculateDistance3D(double x1, double y1, double z1,
24 double x2, double y2, double z2) {
25 return Math.sqrt(Math.pow(x2 - x1, 2) +
26 Math.pow(y2 - y1, 2) +
27 Math.pow(z2 - z1, 2));
28 }
29}2. Compound Interest Calculator
1public class CompoundInterest {
2 public static void main(String[] args) {
3 double principal = 5000;
4 double annualRate = 0.06; // 6%
5 int years = 10;
6 int compoundsPerYear = 12; // Monthly
7
8 // Formula: A = P(1 + r/n)^(nt)
9 double amount = principal * Math.pow(
10 1 + annualRate / compoundsPerYear,
11 compoundsPerYear * years
12 );
13
14 double interest = amount - principal;
15
16 System.out.printf("Principal: $%.2f\n", principal);
17 System.out.printf("Rate: %.1f%%\n", annualRate * 100);
18 System.out.printf("Years: %d\n", years);
19 System.out.printf("Compounds: %d per year\n", compoundsPerYear);
20 System.out.printf("\nFinal Amount: $%.2f\n", amount);
21 System.out.printf("Interest Earned: $%.2f\n", interest);
22
23 // Output:
24 // Principal: $5000.00
25 // Rate: 6.0%
26 // Years: 10
27 // Compounds: 12 per year
28 //
29 // Final Amount: $9096.98
30 // Interest Earned: $4096.98
31 }
32}3. Grade Calculator with Rounding
1public class GradeCalculator {
2 public static void main(String[] args) {
3 int[] scores = {85, 92, 78, 95, 88};
4
5 // Calculate average
6 int sum = 0;
7 for (int score : scores) {
8 sum += score;
9 }
10 double average = (double)sum / scores.length;
11
12 // Find min and max
13 int minScore = scores[0];
14 int maxScore = scores[0];
15 for (int score : scores) {
16 minScore = Math.min(minScore, score);
17 maxScore = Math.max(maxScore, score);
18 }
19
20 // Round average
21 long roundedAvg = Math.round(average);
22
23 System.out.println("Scores: ");
24 for (int score : scores) {
25 System.out.print(score + " ");
26 }
27
28 System.out.printf("\n\nAverage: %.2f\n", average);
29 System.out.println("Rounded: " + roundedAvg);
30 System.out.println("Highest: " + maxScore);
31 System.out.println("Lowest: " + minScore);
32 System.out.println("Range: " + (maxScore - minScore));
33
34 // Letter grade
35 String grade;
36 if (roundedAvg >= 90) grade = "A";
37 else if (roundedAvg >= 80) grade = "B";
38 else if (roundedAvg >= 70) grade = "C";
39 else if (roundedAvg >= 60) grade = "D";
40 else grade = "F";
41
42 System.out.println("Letter Grade: " + grade);
43 }
44}4. Temperature Converter
1public class TemperatureConverter {
2 public static void main(String[] args) {
3 double celsius = 25.0;
4
5 // Celsius to Fahrenheit: F = C × 9/5 + 32
6 double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
7
8 // Celsius to Kelvin: K = C + 273.15
9 double kelvin = celsius + 273.15;
10
11 System.out.printf("%.1f°C = %.1f°F = %.2fK\n",
12 celsius, fahrenheit, kelvin);
13
14 // Round to 1 decimal place
15 fahrenheit = Math.round(fahrenheit * 10.0) / 10.0;
16
17 System.out.println("\nTemperature Conversion Table:");
18 System.out.println("Celsius\tFahrenheit");
19 System.out.println("-------\t----------");
20
21 for (int c = 0; c <= 100; c += 10) {
22 double f = c * 9.0 / 5.0 + 32.0;
23 System.out.printf("%d\t%.1f\n", c, f);
24 }
25 }
26}5. Circle Calculator
1public class CircleCalculator {
2 public static void main(String[] args) {
3 double radius = 7.5;
4
5 // Circumference = 2πr
6 double circumference = 2 * Math.PI * radius;
7
8 // Area = πr²
9 double area = Math.PI * Math.pow(radius, 2);
10
11 // Diameter = 2r
12 double diameter = 2 * radius;
13
14 System.out.println("=== Circle Calculations ===");
15 System.out.printf("Radius: %.1f\n", radius);
16 System.out.printf("Diameter: %.1f\n", diameter);
17 System.out.printf("Circumference: %.2f\n", circumference);
18 System.out.printf("Area: %.2f\n", area);
19
20 // Sphere calculations
21 // Surface area = 4πr²
22 double sphereSurface = 4 * Math.PI * Math.pow(radius, 2);
23
24 // Volume = (4/3)πr³
25 double sphereVolume = (4.0/3.0) * Math.PI * Math.pow(radius, 3);
26
27 System.out.println("\n=== Sphere Calculations ===");
28 System.out.printf("Surface Area: %.2f\n", sphereSurface);
29 System.out.printf("Volume: %.2f\n", sphereVolume);
30 }
31}Common Mistakes
Mistake 1: Forgetting to Cast
1// ❌ WRONG - Integer division
2int result1 = (int)(Math.sqrt(25)); // Unnecessary cast
3double result2 = Math.sqrt(16 / 2); // Wrong! 16/2 = 8 (int division first)
4
5// ✅ CORRECT
6int result1 = (int)Math.sqrt(25); // OK but loses precision
7double result2 = Math.sqrt(16.0 / 2); // Correct: double divisionMistake 2: Radians vs Degrees
1// ❌ WRONG - Using degrees directly
2double result = Math.sin(45); // This is 45 RADIANS, not degrees!
3
4// ✅ CORRECT - Convert to radians
5double result = Math.sin(Math.toRadians(45)); // CorrectMistake 3: Rounding Negative Numbers
1// Be aware of rounding behavior
2System.out.println(Math.round(-3.5)); // -3 (not -4!)
3System.out.println(Math.ceil(-3.1)); // -3.0 (toward positive)
4System.out.println(Math.floor(-3.1)); // -4.0 (toward negative)Mistake 4: Random Range Errors
1// ❌ WRONG - Off by one
2int wrong = (int)(Math.random() * 10); // 0-9, not 1-10!
3
4// ✅ CORRECT - For 1-10
5int correct = (int)(Math.random() * 10) + 1;
6
7// For range [min, max]
8int range = (int)(Math.random() * (max - min + 1)) + min;Quick Reference Guide
Commonly Used Methods
1// Basic Math
2Math.abs(-5) → 5
3Math.max(10, 20) → 20
4Math.min(10, 20) → 10
5Math.pow(2, 3) → 8.0
6Math.sqrt(16) → 4.0
7
8// Rounding
9Math.round(3.7) → 4
10Math.ceil(3.1) → 4.0
11Math.floor(3.9) → 3.0
12
13// Random
14Math.random() → 0.0 to 0.999...
15(int)(Math.random()*10) → 0 to 9
16(int)(Math.random()*10)+1 → 1 to 10
17
18// Constants
19Math.PI → 3.14159...
20Math.E → 2.71828...
21
22// Trigonometry (in radians!)
23Math.sin(Math.toRadians(90)) → 1.0
24Math.cos(Math.toRadians(0)) → 1.0
25Math.tan(Math.toRadians(45)) → 1.0Practice Exercises
Exercise 1: BMI Calculator
Create a program to calculate Body Mass Index.
Solution
1public class BMICalculator {
2 public static void main(String[] args) {
3 double weightKg = 70;
4 double heightM = 1.75;
5
6 // BMI = weight / height²
7 double bmi = weightKg / Math.pow(heightM, 2);
8 double roundedBMI = Math.round(bmi * 10.0) / 10.0;
9
10 System.out.printf("Weight: %.1f kg\n", weightKg);
11 System.out.printf("Height: %.2f m\n", heightM);
12 System.out.printf("BMI: %.1f\n", roundedBMI);
13
14 String category;
15 if (bmi < 18.5) category = "Underweight";
16 else if (bmi < 25) category = "Normal";
17 else if (bmi < 30) category = "Overweight";
18 else category = "Obese";
19
20 System.out.println("Category: " + category);
21 }
22}Exercise 2: Dice Game
Simulate rolling two dice and calculate sum.
Solution
1public class DiceGame {
2 public static void main(String[] args) {
3 int die1 = (int)(Math.random() * 6) + 1;
4 int die2 = (int)(Math.random() * 6) + 1;
5 int sum = die1 + die2;
6
7 System.out.println("Die 1: " + die1);
8 System.out.println("Die 2: " + die2);
9 System.out.println("Sum: " + sum);
10
11 if (sum == 7 || sum == 11) {
12 System.out.println("You win!");
13 } else if (sum == 2 || sum == 3 || sum == 12) {
14 System.out.println("You lose!");
15 } else {
16 System.out.println("Roll again!");
17 }
18 }
19}Exercise 3: Quadratic Formula
Solve ax² + bx + c = 0
Solution
1public class QuadraticSolver {
2 public static void main(String[] args) {
3 double a = 1, b = -3, c = 2; // x² - 3x + 2 = 0
4
5 // Discriminant = b² - 4ac
6 double discriminant = Math.pow(b, 2) - 4 * a * c;
7
8 System.out.printf("Equation: %.0fx² + %.0fx + %.0f = 0\n", a, b, c);
9 System.out.println("Discriminant: " + discriminant);
10
11 if (discriminant > 0) {
12 double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
13 double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
14 System.out.println("Root 1: " + root1);
15 System.out.println("Root 2: " + root2);
16 } else if (discriminant == 0) {
17 double root = -b / (2 * a);
18 System.out.println("One root: " + root);
19 } else {
20 System.out.println("No real roots");
21 }
22 }
23}Summary
Most Common Methods:
- ›
abs()- Absolute value - ›
max(),min()- Find extremes - ›
pow(),sqrt()- Powers and roots - ›
round(),ceil(),floor()- Rounding - ›
random()- Random numbers
Remember:
- ›Math methods are static - no object needed
- ›Trig functions use radians, not degrees
- ›
round()returnslong, notdouble - ›Random is [0.0, 1.0) - exclusive of 1.0
Common Formulas:
- ›Distance:
sqrt(pow(x2-x1, 2) + pow(y2-y1, 2)) - ›Random range:
(int)(random() * (max-min+1)) + min - ›Compound interest:
P * pow(1 + r/n, n*t) - ›Circle area:
PI * pow(radius, 2)
Master these Math methods and calculations become simple! 🚀