The Math Class
Part of: Using Objects
A Toolbox of Static Methods The Math class provides common mathematical operations. Its methods are static , meaning you call them on the class name itself, not on an object: Math.methodName(...). You never write new Math(). Core AP Methods The AP CSA subset includes four Math methods you must know: Key type details: - abs returns the same type you pass (int - int, double - double). - pow and sqrt always return a double , even for whole results. Math.pow(2,3) is 8.0, not 8. - random returns a double that is = 0.0 and strictly < 1.0. Generating Random Integers Math.random() alone gives a fraction. The standard AP formula for a random int in a range [low, high] (inclusive) is: The cast (int) truncates toward zero. Multiplying by range spreads the fraction across 0..range-1; adding low shifts it. Casting Math Results Because pow and sqrt give doubles, you often cast back to int when you need a whole number: Remember that casting truncates , it does not round. (int) 7.9 is 7. To round, you would add 0.5 before casting or use rounding logic. Why Static? Math operations need no stored state, sqrt(9) is always 3.0. Static methods belong to the class as shared utilities, so calling Math.sq
Challenge: Hypotenuse Floor