java.math.BigInteger toString() and toString(int radix)
Description
- toString()
- toString(int radix)
The first method toString() with method argument returns the String representation of this BigInteger meanwhile the second method toString(int radix) will return the String representation of this BigInteger in a given radix. The second method is very similar in nature with the toString(int radix) method of the Integer class.
Since the first method is a straight forward conversion, I will focus the discussion on the second method which takes into account the radix. For example if we have a BigInteger value of 12 and the radix would be 16 which pertains to hexadecimal. In hexadecimal the value 12 is equal to C, thus the returned String by this method would be 12.
Notes:
- Overloaded methods are those methods that have the same method name but with different signatures.
Method Syntax
The following are the overloaded toString() methods:
1.
public String toString()
2.
public String toString(int radix)
Method Argument
- toString(int radix)
Data Type | Parameter | Description |
---|---|---|
int | radix | radix of the String representation. |
Method Returns
The toString() method returns the decimal String representation of this BigInteger. Meanwhile the toString(int radix) returns String representation of this BigInteger in the given radix.
Compatibility
Requires Java 1.1 and up
Java BigInteger toString() Example
Below is a java code demonstrates the use of toString() method of BigInteger class. The example presented might be simple however it shows the behavior of the toString() method.
package com.javatutorialhq.java.examples; import java.math.BigInteger; import java.util.Arrays; import java.util.Scanner; /* * A java example source code to demonstrate * the use of toString() method of BigInteger class */ public class BigIntegerToStringExample { 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(); System.out.print("Enter the desired radix:"); String radix = s.nextLine(); s.close(); // convert the first String Input to BigInteger BigInteger val1 = new BigInteger(input); // convert the radix input into Integer Integer radixInteger = Integer.parseInt(radix); // Print the toString() result System.out.println("toString() result is:" + val1.toString()); System.out.println("toString(" + radix + ") is:" + val1.toString(radixInteger)); } }