Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

Java – Find Absolute Value of Double – abs() Method with Examples

java.lang.Math.abs() method is used to find the absolute value of a double number for the given input (x – parameter) in Java. If argument is not negative, the argument is returned as it is, but if the argument is negative then the negation of argument is returned.

Package

abs() method exists in Math class of java.lang package.
Since: JDK1.0

 

Declaration of abs() Method

The declaration of abs() method is:

 

Syntax of abs() Method

The syntax of abs() method in Java is:

Example

Output:
632.432516

Example
By importing java.lang package the syntax of abs() method can be used as:

Output:
385.723

 

Special Cases of abs() Method in Java

If the argument is positive zero or negative zero, the result is positive zero.
If the argument is infinite, the result is positive infinity.
If the argument is NaN, the result is NaN.
Example

Output:
0.0
0.0
Infinity
Infinity
NaN

 

Parameters of abs() Method in Java

x – Where x is any valid double input value. This parameter is required.

 

Error Handling

If the x parameter is not a number abs() method returns an error.
If there is no argument (x – input value) passes to the method, the compiler will produce an error.
Example

Output:
Error

 

Return Value of abs() Method in Java

abs() method returns the absolute value of a double number for the given input (x – parameter).

 

Java abs() Method Example 1


Output:
absolute value of a Negative Value: 367.344
absolute value of a Positive Value: 6258.3825
absolute value of Zero: 0.0

 

Java abs() Method Example 2


Output:
1.7976931348623157E308
4.9E-324
NaN
1022.0
1.8393666E-12
351.7569
0.0
7.4444
2113729.4

 

LearnAndLearn.com © 2018 - All rights reserved