java.lang.StrictMath abs​(long a)

Description

The abs​(long a) method of StrictMath class returns the absolute value of a long value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.

Note that if the argument is equal to the value of Long.MIN_VALUE, the most negative representable long value, the result is that same value, which is negative.

Notes:

The abs​(long a) method of StrictMath class is static thus it should be accessed statically which means the we would be calling this method in this format:

StrictMath.abs​(long a)

Non static method is usually called by just declaring method_name(argument) however in this case since the method is static, it should be called by appending the class name as suffix. We will be encountering a compilation problem if we call the java compare method non statically.

Method Syntax

public static long abs​(long a)

Method Argument

Data Type Parameter Description
long a the argument whose absolute value is to be determined.

Method Returns

The abs​(long a) method returns the absolute value of the argument.

Compatibility

Requires Java 1.3 and up

Java StrictMath abs​(long a) Example

Below is a java code demonstrates the use of abs​(long a) method of StrictMath class. Bssically it takes a long input from user and then it displays the absolute value of the long input.

package com.javatutorialhq.java.examples;


import java.util.Scanner;

/*
 * A java example source code to demonstrate
 * the use of abs​(long a) method of Math class
 */

public class StrictMathAbsLongExample {

	public static void main(String[] args) {
		
		// Ask user input (long datatype)
		System.out.print("Enter a long:");
		
		// declare the scanner object
		Scanner scan = new Scanner(System.in);		
		
		// use scanner to get the user input and store it to a variable
		long longValue = scan.nextLong();			
		
		// close the scanner object
		scan.close();		
		
		// get the absolute value of the user input
		long result = StrictMath.abs(longValue);
		
		// print the result
		System.out.println("result: "+result);

	}

}

Sample Output

Below is the sample output when you run the above example.

Java StrictMath abs (long a) method example output