Languages
[Edit]
EN

Java - Math.abs() method example

3 points
Created by:
Palusbug
515

The Math.abs() function returns the absolute value of a number. 

The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.

Popular usage examples:

1. Documentation

Edit
Syntax

Note: Classes in the java.lang package are imported automatically, so it is not necessary to do it manually - we use just Math.abs() call.

Parametersnumber - double, float, int, or long value (primitive value).
ResultThe absolute value calculated from the number (primitive value).
Description

Math.abs() is a static method that takes only one parameter and returns absolute number parameter value. The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.

2. Math.abs() custom implementation

Note: there are few ways to change sign to opposite if (x < 0) is true:
  • x = -x
  • x *= -1
  • x = ~x + 1(not for double)

References

Edit
  1. Absolute value - wikipedia
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - Math object

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join