← Back to course

Math Class & Wrapper Classes

You’ll be able to

The Math class: static helpers

The Math class is a collection of static utility methods you call on the class itself, not on an object: Math.abs(-4), Math.max(2, 5), Math.min(2, 5), Math.pow(2, 3). Because they are static, there is no new Math() — you write the class name, a dot, and the method. Math.abs returns the magnitude, Math.max/Math.min pick the larger/smaller of two values, and Math.pow(b, e) returns b raised to the e (as a double).

Integer division truncates

When both operands are int, the / operator does integer division: the result is an int with the fractional part thrown away (truncated toward zero), not rounded. So 7 / 2 is 3, not 3.5. To get a decimal result, at least one operand must be a double, as in 7.0 / 2, which yields 3.5. The related % operator gives the remainder: 7 % 2 is 1.

Wrapper classes: Integer and Double

Primitives like int and double are not objects, but sometimes an object is required (for example, inside an ArrayList). The wrapper classes Integer and Double box a primitive into an object. Java autoboxes for you: Integer n = 5; wraps the int 5, and it unboxes automatically when you use it in arithmetic. Wrappers also hold useful constants and parsing methods, such as Integer.parseInt("42").

Integer vs. double division
7 / 2 = 3 (int) 7.0 / 2 = 3.5 (double)
If both operands are int, the result is truncated to an int. One double operand promotes the whole operation to double.
Worked example

Trace this code: System.out.println(Math.abs(-4) + Math.max(2, 5));

  1. 1.Evaluate Math.abs(-4): the absolute value of -4 is 4.
  2. 2.Evaluate Math.max(2, 5): the larger of 2 and 5 is 5.
  3. 3.Add the two results: 4 + 5 equals 9, which is printed.
Answer: It prints 9 — the absolute value 4 plus the maximum 5.
Checkpoint

What does this print? `System.out.println(7 / 2);`

Watch out

Integer division truncates toward zero — it does not round. 7 / 2 is 3, and even 9 / 10 is 0. If you need a decimal, make one operand a double (e.g. 7.0 / 2).

Checkpoint

What does this print? `System.out.println(Math.abs(-4) + Math.max(2, 5));`

On the exam

Math methods are static: always call them as Math.name(...), never on an object. And watch the return type — Math.pow returns a double, so Math.pow(2, 3) is 8.0, not 8.

Answer the 2 checkpoints as you read.

Sign in to save your progress