TOPIC 1.11 · STUDY

Math Class

Math methods are class methods on Math. Call them as Math.abs, Math.sqrt, Math.pow, and Math.random. abs matches its argument type. sqrt and pow always return double. random returns a double in [0.0, 1.0). Casting a double to int truncates toward zero.

1.11.A

Math class methods

The Math class supplies useful numeric operations as class methods. You do not create a Math object. Call each method with the class name, a dot, and the method name, such as Math.abs, Math.sqrt, Math.pow, and Math.random.

int magnitude = Math.abs(-19);
double root = Math.sqrt(81);
double scaled = Math.pow(2, 4);
int clipped = (int) Math.sqrt(20);

Math.abs(-19) with an int argument returns the int 19. Math.abs on a double argument returns a double. Math.sqrt always returns a double, so Math.sqrt(81) is 9.0, not the int 9. Math.pow(2, 4) is 16.0 as a double. Casting a double to int with (int) drops the fractional part toward zero: (int) Math.sqrt(20) is 4 because the square root is a little more than 4 but less than 5.

Method Argument idea Return type
Math.abs A number whose sign you want removed Same kind as the argument (int or double)
Math.sqrt A nonnegative value whose square root you need double
Math.pow A base and an exponent double
Math.random No arguments; each call draws a new sample double in [0.0, 1.0)
Three short flows stacked: Math.abs(-19) yields 19, Math.sqrt(81) yields 9.0, and Math.pow(2, 4) yields 16.0.

Each call sits on the left. The value on the right is what that call returns, including the .0 when the result is a double.

Math.random() returns a double greater than or equal to 0.0 and strictly less than 1.0. Scale it to a wider interval by multiplying: Math.random() * 8 is in [0.0, 8.0). Cast that product to int to get whole numbers from 0 up to, but not including, the multiplier. Add a shift afterward when you need a different inclusive range, such as (int)(Math.random() * 6) + 4 for the integers 4 through 9.

double unit = Math.random();
int zeroToSeven = (int) (Math.random() * 8);
int fourToNine = (int) (Math.random() * 6) + 4;

Key points

  • Call Math methods with the class name: Math.abs, Math.sqrt, Math.pow, Math.random.
  • Math.abs on an int returns an int; Math.abs on a double returns a double.
  • Math.sqrt and Math.pow return double, even when the math result looks whole.
  • Casting a double to int with (int) truncates toward zero.
  • Math.random() is in [0.0, 1.0). Multiply, cast, then optionally add a shift for an integer range.

sqrt and pow return double even when the mathematical result is a whole number. Math.sqrt(81) is 9.0 and Math.pow(2, 4) is 16.0. Assigning either result to an int variable requires an explicit cast.

Practice this topic