Learn and Learn

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

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

java.lang.Math.abs() method is used to find the absolute value of an integer 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.

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:

487

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

Output:

68

 

Special Cases of abs() Method in Java

Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
Example 

Parameters of abs() Method in Java

x – Where x is any valid int 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 int value for the given input (x – parameter).

 

Java abs() Method Example 1


Output:

absolute value of a Negative Value: 18
absolute value of a Positive Value: 27
absolute value of Zero: 0

 

LearnAndLearn.com © 2018 - All rights reserved