Finding the absolute value in Java

In mathematics, the absolute value of a number is its non-negative value, i.e. the absolute value of -2 is 2.

Absolute value in Java

In order to retrieve the absolute value in Java, we use the abs() function.

svg viewer

Syntax

The general syntax of the abs() function is:

public static datatype abs(datatype number)

Parameters

The function takes as input the argument whose absolute value is to be determined.

Return value

The function returns the absolute value of the argument.

Example

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) );
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved