Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

strictmath
java
communitycreator

What is StrictMath.abs method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The StrictMath class as utility methods is used for performing basic numeric operations. It is present in the java.lang package.

Note: Read more about the StrictMath class here.

The abs method can be used to get the absolute value of the passed value.

Syntax

This method has four overridden methods:

public static double abs(double a)
public static float abs(float a)
public static int abs(int a)
public static long abs(long a)

Return value

  • If the argument is negative, then the argument’s negation is returned ( the negative value is converted to a positive value).

  • If the argument is positive then the same value is returned.

  • If the argument is NaN then NaN is returned.

Code

The below code explains how to use the abs method:

class StrictMathAbsExample {
public static void main( String args[] ) {
// create one double and one int variable
double val1 = -10.45;
int val2 = 10;
// use StrictMath.abs method
System.out.println("StrictMath.abs(-10.45) : " + StrictMath.abs(val1));
System.out.println("StrictMath.abs(10) : " + StrictMath.abs(val2));
}
}
Using the StrictMath.abs to get absolute vlaue

Explanation

In the above code:

  • Lines 4 and 5: We create one double variable val1 and one int variable val2 with values -10.45 and 10, respectively.

  • Line 7: We use the abs method of the StrictMath class to get the absolute value of the val1 variable. The val1 contains the negative value -10.45 so the abs method returns the negation of the value( 10.45).

  • Line 8: We use the abs method of the StrictMath class to get the absolute value of the val2 variable. The val2 contains the positive value 10 so, the same value is returned.

RELATED TAGS

strictmath
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring