Code Logo

Absolute Value with Math.abs()

Published at25 Jul 2026
Java OOP Easy 0 views
Like0

Write a Java function that takes an integer and returns its absolute value using Math.abs(). The absolute value is the non-negative value of a number without regard to its sign.

Math.abs() is a static method in Java's Math class that returns the absolute value of an int, long, float, or double argument. For int arguments, if the argument is Integer.MIN_VALUE (-2147483648), the result is that same negative value because the positive equivalent (2147483648) exceeds the int range. This is a known edge case in Java's Math.abs().

The Math class in Java provides a comprehensive set of mathematical functions: abs(), min(), max(), pow(), sqrt(), sin(), cos(), random(), and many more. All methods are static and can be called directly without creating a Math instance. Math is declared as a final class with a private constructor.

Time complexity is O(1). Space complexity is O(1). Math.abs() compiles to a single CPU instruction on most architectures, making it extremely fast.

Edge cases include zero (absolute value is 0), positive numbers (unchanged), negative numbers (become positive), and Integer.MIN_VALUE (returns itself, not positive).

Example Input & Output

Example 1
Input
42
Output
42
Explanation

Positive unchanged

Example 2
Input
-1
Output
1
Explanation

Absolute of -1 is 1

Example 3
Input
0
Output
0
Explanation

Zero absolute is 0

Example 4
Input
3
Output
3
Explanation

Positive stays same

Example 5
Input
-5
Output
5
Explanation

Absolute of -5 is 5

Algorithm Flow

Recommendation Algorithm Flow for Absolute Value with Math.abs()
Recommendation Algorithm Flow for Absolute Value with Math.abs()

Solution Approach

class Solution {
    public int solution(int n) {
        return Math.abs(n);
    }
}

Best Answers

java - Approach 1
class Solution {
    public int solution(int n) {
        return Math.abs(n);
    }
}