Math Class & Wrapper Classes
- Call static Math methods such as `abs`, `max`, `min`, and `pow`
- Predict results of integer division and how it differs from double division
- Recognize the Integer and Double wrapper classes for boxing primitives
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").
Trace this code: System.out.println(Math.abs(-4) + Math.max(2, 5));
- 1.Evaluate
Math.abs(-4): the absolute value of-4is4. - 2.Evaluate
Math.max(2, 5): the larger of2and5is5. - 3.Add the two results:
4 + 5equals9, which is printed.
9 — the absolute value 4 plus the maximum 5.What does this print? `System.out.println(7 / 2);`
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).
What does this print? `System.out.println(Math.abs(-4) + Math.max(2, 5));`
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