Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
absolute value
abs
absolute

Finding the absolute value in Java

Educative Answers Team

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) );
  }
}

RELATED TAGS

java
absolute value
abs
absolute
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring