java.math.BigInteger abs()
Description
On this document we will be showing a java example on how to use the abs() method of BigInteger Class. Basically this method returns the absolute value of this BigInteger object. This is very useful if we are dealing only with unsigned integer.
Method Syntax
public BigInteger abs()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The abs() method returns the absolute value of this BigInteger in short abs(this).
Compatibility
Requires Java 1.1 and up
Java BigInteger abs() Example
Below is a java code demonstrates the use of abs() method of BigInteger class. The example presented might be simple however it shows the behavior of the abs() method.
package com.javatutorialhq.java.examples; import java.math.BigInteger; import java.util.Scanner; /* * A java example source code to demonstrate * the use of abs() method of BigInteger class */ public class BigIntegerAbsExample { public static void main(String[] args) { // get user input System.out.print("Enter a value:"); Scanner s = new Scanner(System.in); String input = s.nextLine(); s.close(); // declare a new BigInteger BigInteger val1 = new BigInteger("-1245"); // convert string input to BigInteger BigInteger val2 = new BigInteger(input); // get the absolute value of both the BigInteger and print it System.out.println("Absolute value of val1="+val1.abs()); System.out.println("Absolute value of val2="+val2.abs()); } }
This example is a lot simpler than it looks. Basically we ask for user input and converted this value into BigInteger. Another BigInteger object were also intialize with constructor having a value of “-1245”. We then use the abs() method to get the absolute value of both the input.