How to get the absolute value of a number in java

This example shows you how to get the absolute value of a number in java.

To get the absolute value or the abs value of a number we use the Math.abs() method call. The Math.abs() method is an overloaded that can accept value in type of double, float, int or long.

Below is the example code which gets the absolute value.

package com.java.connect.math;
 
//How to get the absolute value of a number in java
public class AbsoluteValueExample {
    public static void main(String[] args) {
        Double value = -105.0D;
 
        int absolute3 = Math.abs(value.intValue());
        System.out.println("Absolute value in int is : " + absolute3);
 
        long absolute4 = Math.abs(value.longValue());
        System.out.println("Absolute value in long is : " + absolute4);
 
        double absolute1 = Math.abs(value);
        System.out.println("Absolute value in double is : " + absolute1);
 
        float absolute2 = Math.abs(value.floatValue());
        System.out.println("Absolute value in float is : " + absolute2);
 
        long absolute5 = Math.abs(value.shortValue());
        System.out.println("Absolute value in short is : " + absolute5);
 
    }
}

The output of the above example will be as:

Absolute value in int is : 105
Absolute value in long is : 105
Absolute value in double is : 105.0
Absolute value in float is : 105.0
Absolute value in short is : 105