Learn and Learn

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

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

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

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:

4876.1875

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

Output:

68.97

 

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 float 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 float value for the given input (x – parameter).

 

Java abs() Method Example 1


Output:

absolute value of a Negative Value: 18.869
absolute value of a Positive Value: 27.78639
absolute value of Zero: 0.0

 

Java abs() Method Example 2


Output:

3.4028235E38
1.4E-45
NaN
126.0
4.2867E-11
16.852
0.0
2.58
7.8856902E8

 

Loading...
LearnAndLearn.com © 2018 - All rights reserved