In mathematics, the absolute value of a number is its non-negative value, i.e. the absolute value of -2 is 2.
In order to retrieve the absolute value in Java, we use the abs()
function.
The general syntax of the abs()
function is:
public static datatype abs(datatype number)
The function takes as input the argument whose absolute value is to be determined.
The function returns the absolute value of the argument.
Let’s take a look at how we can find the absolute value using the abs()
function!
class HelloWorld { public static void main( String args[] ) { /* Converting Integer values */ int x = 123; int y = -789; System.out.printf( "Absolute Value of x: %d \n", Math.abs(x) ); System.out.printf( "Absolute Value of y: %d \n", Math.abs(y) ); /* Converting Floating Point values */ float a = 1.23f; float b = -7.9f; System.out.printf( "Absolute Value of a: %f \n", Math.abs(a) ); System.out.printf( "Absolute Value of b: %f \n", Math.abs(b) ); } }
RELATED TAGS
View all Courses