AP® Computer Science A · Unit 1 · Topic 1.11

The Math Class

The Math class is a toolbox of static methods for common calculations like powers, square roots, and absolute value, so you don't have to write that logic yourself. Math.pow and Math.sqrt always return a double, even when the inputs are ints.

Java doesn't give you operators for things like square roots or exponents the way it gives you + and -. Those operations are less common and more specialized, so instead Java bundles them into the Math class: a collection of ready-made static methods you call by name. Math.abs(x) takes a number and strips its sign, reflecting negative values across zero to land on the positive side of the number line. Math.√x finds the value that, multiplied by itself, gives x, moving you from a point on the number line down to its root. Math.pow(base, exponent) scales a number up by repeated multiplication, moving it far out along the line as the exponent grows.

Here's the part that trips people up: Math.pow and Math.sqrt are declared to return double, no matter what type you feed them. Math.pow(2, 3) looks like it should give you the int 8, but Java doesn't check your inputs to decide the output type. It checks the method's declared return type, which is always double for these two. That means int result = Math.pow(2, 3); will not compile, because Java refuses to quietly squeeze a double into an int. You have to cast it yourself: int result = (int) Math.pow(2, 3);.

This matters because it's your first real encounter with a method that has a fixed, non-obvious return type, which sets up everything later about reading method signatures before trusting what a call 'looks like' it returns. It also reinforces the casting rules from expressions: widening happens automatically, narrowing needs an explicit cast, and Math methods are a reliable place that rule shows up on every call.

Key terms

static method
A method that belongs to the class itself, callable as Math.√x without creating a Math object.
Math.pow(base, exponent)
Returns base raised to the power of exponent, always as a double.
Math.√x
Returns the square root of x as a double.
narrowing
Converting a larger type like double into a smaller one like int, which loses precision and needs an explicit cast.
cast
An explicit instruction like (int) that forces a value to be treated as a different type.

Watch it explained

  1. How it worksHow do Math.abs, Math.pow, and Math.sqrt each transform a value on a number line?
  2. Worked exampleFind the value of Math.pow(2, 10) and of Math.√144, and the type each returns.
  3. Worked exampleFind how (int) Math.pow(3, 4) differs from Math.pow(3, 4) when you print both.
  4. Common mistakeWhy isn't Math.pow(2, 3) an int, when both arguments look like plain ints?

Check yourself

Your turn1 of 2
What does Math.pow(3, 3) + Math.√93 evaluate to?

End of topic.