EN
Java - Math.abs() method example
3 points
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:
xxxxxxxxxx
1
public class MathExample {
2
3
public static void main(String[] args) {
4
System.out.println( Math.abs(2) ); // 2
5
System.out.println( Math.abs(-2) ); // 2
6
7
System.out.println( Math.abs(2.54) ); // 2.54
8
System.out.println( Math.abs(-2.54) ); // 2.54
9
10
System.out.println( Math.abs(0) ); // 0
11
System.out.println( Math.abs(3 + 5) ); // 8
12
System.out.println( Math.abs(3 - 5) ); // 2
13
}
14
}
Syntax |
xxxxxxxxxx 1 package java.lang; 2 3 public final class Math { 4 5 public static int abs(int number) { ... } 6 public static long abs(long number) { ... } 7 public static float abs(float number) { ... } 8 public static double abs(double number) { ... } 9 10 }
|
Parameters | number - double , float , int , or long value (primitive value). |
Result | The absolute value calculated from the number (primitive value). |
Description |
|
2. Math.abs() custom implementation
xxxxxxxxxx
1
public class CustomMath {
2
3
static double abs(double x) {
4
if (x < 0) {
5
return -x;
6
}
7
return x;
8
}
9
10
public static void main(String[] args) {
11
System.out.println( abs(2.0) ); // 2.0
12
System.out.println( abs(-2.0)); // 2.0
13
System.out.println( abs(0.0) ); // 0.0
14
}
15
}
Note: there are few ways to change sign to opposite if(x < 0)
istrue
:
x = -x
x *= -1
x = ~x + 1
(not for double)