🧮 Object-Oriented Programming

Mathematical Library Methods

⏱ 2 hr2 topicsInteractive
🎯 By the end: You can use the common Math class methods and convert a maths formula into a correct Java expression.

Java provides ready-made calculations in the Math class, part of the java.lang package. Because java.lang is imported automatically, you can use Math without any import (ICSE Class 9).

1The Math class methods

Call these on the class name Math. Each returns a result:

MethodReturnsExample
Math.pow(a, b)a to the power bMath.pow(2, 3) = 8.0
Math.sqrt(x)Square rootMath.sqrt(25) = 5.0
Math.cbrt(x)Cube rootMath.cbrt(27) = 3.0
Math.abs(x)Absolute (positive) valueMath.abs(-7) = 7
Math.max(a,b) / Math.min(a,b)Larger / smallerMath.max(4, 9) = 9
Math.ceil(x)Rounds UP to a whole numberMath.ceil(4.1) = 5.0
Math.floor(x)Rounds DOWNMath.floor(4.9) = 4.0
Math.round(x)Rounds to the NEAREST wholeMath.round(4.5) = 5
Math.random()A random decimal from 0 up to (not including) 10.37…
Note the rounding trio: ceil always goes up, floor always goes down, round goes to the nearest.
Key points
  • Math methods are called on the class: Math.sqrt(25), Math.pow(2,3).
  • ceil rounds up, floor rounds down, round goes to the nearest whole.
  • Math.random() gives a decimal from 0 up to (not including) 1; pow/sqrt/cbrt/abs/max/min do the obvious maths.

2Formulas into Java expressions

To use a maths formula in Java, rewrite it with operators and Math methods:

MathsJava
area = π r²area = 3.14 * Math.pow(r, 2);
c = √(a² + b²)c = Math.sqrt(Math.pow(a,2) + Math.pow(b,2));
avg = (a + b + c) / 3avg = (a + b + c) / 3.0;
Watch integer division: 5 / 2 gives 2 (not 2.5) because both are ints. Use a decimal — 5 / 2.0 — to get 2.5. Use brackets to keep the order of operations correct.
Key points
  • Replace powers with Math.pow and roots with Math.sqrt; keep brackets to preserve order.
  • Integer division drops the decimal: 5 / 2 = 2; use 5 / 2.0 for 2.5.
  • Test the expression with known numbers to check it's right.

★ Practical: calculate with Math

In BlueJ, write programs that:

  1. Read a number and print its square root and its cube.
  2. Read two numbers and print the larger using Math.max.
  3. Show the difference between Math.ceil, Math.floor and Math.round on 4.5.
  4. Compute the hypotenuse √(a² + b²) of a right triangle from two inputs.

Ready for the chapter test?

Answer 5 questions. Score 60% or more to mark this chapter complete.

Start the test →

💡 Log in to save your progress and earn the certificate.