Home >>Java Math Methods >Java Math.abs() method

Java Math.abs() method

Java Math.abs() method

Java Math.abs() method is used to returns the absolute (Positive) value of a value int. This approach gives the statement its absolute value. The statement could be int, double, long, or float.

Syntax

public static int abs(int i)  
public static double abs(double d)  
public static float abs(float f)  
public static long abs(long lng)  

Parameters

The argument whose absolute value is to be determined

Returns

This method is used to returns the absolute value of the argument

  1. If we give as argument positive or negative value, this approach must result in positive value.
  2. If Infinity is the statement, the approach will result in Positive Infinity.
  3. This method returns -1 if the statement is -1.
  4. If the argument is equal to the value of Integer. MIN VALUE or Long. MIN VALUE, the most negative int value or long value representable, the consequence is the same value, which is negative.

Java Math.abs() Method Example 1


public class MyClass  
{  
    public static void main(String args[])  
    {  
        int x = 12;  
        int y = -42;  
        System.out.println(Math.abs(x));  
        System.out.println(Math.abs(y));  
        System.out.println(Math.abs(Integer.MIN_VALUE));  
    }  
}  

Output:
12
42
-2147483648

Java Math.abs() Method Example 2


public class MyClass   
{   
    public static void main(String args[])  
    {  
        double x = -12.76;  
        double y = -23.67;  
        System.out.println(Math.abs(x));  
        System.out.println(Math.abs(y));  
        System.out.println(Math.abs(5.0 / 0));     
    }  
}  

Output:
12.76
23.67
Infinity

No Sidebar ads