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