Java Math abs method example shows how to find the absolute value of an int, float, double or long number using the abs method of Java Math class.
How to find the absolute value of a number using the abs method in Java?
We can use the abs
method of the Math class to get the absolute value of a number.
1 |
public static int abs(int i) |
The abs
method is overloaded for float, double, long, and int types. That means you can use the same method to get absolute value of float, double, long, and int numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.javacodeexamples.mathexamples; public class FindAbsoluteValueExample { public static void main(String[] args){ int[] intNumbers = { -123, 123, 0, Integer.MIN_VALUE, Integer.MAX_VALUE }; System.out.println("Absolute value of int numbers:"); for( int i : intNumbers ){ System.out.println( Math.abs(i) ); } float[] floatNumbers = { 12.34f, -12.34f, Float.MIN_VALUE, Float.MAX_VALUE }; System.out.println("Absolute value of float numbers:"); for( float f : floatNumbers ){ System.out.println( Math.abs(f) ); } long[] longNumbers = { 21344234234l, -21344234234l, Long.MIN_VALUE, Long.MAX_VALUE }; System.out.println("Absolute value of long numbers:"); for( long l : longNumbers ){ System.out.println( Math.abs(l) ); } double[] doubleNumbers = { 23434.2321, -23434.2321, Double.MIN_VALUE, Double.MAX_VALUE }; System.out.println("Absolute value of double numbers:"); for( double d : doubleNumbers ){ System.out.println( Math.abs(d) ); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Absolute value of int numbers: 123 123 0 -2147483648 2147483647 Absolute value of float numbers: 12.34 12.34 1.4E-45 3.4028235E38 Absolute value of long numbers: 21344234234 21344234234 -9223372036854775808 9223372036854775807 Absolute value of double numbers: 23434.2321 23434.2321 4.9E-324 1.7976931348623157E308 |
You might be wondering why the absolute value of Integer.MIN_VALUE
is -2147483648 instead of +2147483648. That is because an int is represented in Java by 32 bits and the highest value it can hold is +2147483647. Trying to represent +2147483648 number, it overflows and rolls over to -2147483648. This is the same case with the float, double and long types as well.
This example is a part of the Java Math class tutorial with examples.
Please let me know your views in the comments section below.