The Java Math class provides a variety of methods that allow you to perform mathematical operations on numbers.
Math.max(x, y)
The Math.max(x, y)
method is used to find the highest value between x and y:
// Example int highestSpeed = Math.max(120, 150); // Maximum speed between two vehicles
Math.min(x, y)
The Math.min(x, y)
method is used to find the lowest value between x and y:
// Example int lowestSpeed = Math.min(60, 90); // Minimum speed between two vehicles
Math.sqrt(x)
The Math.sqrt(x)
method returns the square root of x:
// Example double engineEfficiency = Math.sqrt(49); // Square root calculation for efficiency rating
Math.abs(x)
The Math.abs(x)
method returns the absolute (positive) value of x:
// Example double distanceDifference = Math.abs(-35.7); // Absolute value of distance difference
Random Numbers
The Math.random()
method returns a random number between 0.0 (inclusive) and 1.0 (exclusive):
// Example double randomValue = Math.random(); // Generates a random number
To gain more control over the random number, such as generating a number between 0 and 100, you can use the following formula:
// Example int randomMileage = (int)(Math.random() * 101); // Random mileage between 0 and 100