Convert BigInteger to String in Java [3 ways]

In this post, I will be sharing how to convert BigInteger to String in Java with examples. There are 3 ways to achieve our goal of converting BigInteger to String in Java:

1. Using String class valueOf() method [Recommended]

2. Using BigInteger class toString() method

3. Using BigInteger class toByteArray() method

Read Also: Convert String to BigInteger in Java

Let's dive deep into the topic:

Convert BigInteger to String in Java

1. Using String class valueOf() method


You can use the String class valueOf() method to convert BigInteger to String in Java. Internally, String class valueOf() method calls toString() method.

Note: One major difference between valueOf() and toString() methods is String class valueOf() method can deal with the null values where as toString() method throws NullPointerException.


import java.math.BigInteger;
public class BigIntegerToString {
  public static void main(String args[])
  {
      BigInteger num = new BigInteger("12345");
      String str = String.valueOf(num);
      System.out.println("Converted BigInteger to String: " + str);
  }
}


Output:
Converted BigInteger to String: 12345


2. Using BigInteger class toString() method


You can easily use BigInteger class toString() method to convert BigInteger to String in Java as shown in the below example:

import java.math.BigInteger;
public class BigIntegerToString2 {
  public static void main(String args[])
  {
      BigInteger num = new BigInteger("78970");
      String str = num.toString();
      System.out.println("Converted BigInteger to String: " + str);
  }
}


Output:
Converted BigInteger to String: 78970


3. Using BigInteger class toByteArray() method


You can easily convert BigInteger to String by using BigInteger class toByteArray() method. First, convert BigInteger to byte array and then byte array to String as shown below in the example:

import java.math.BigInteger;
public class BigIntegerToString3 {
  public static void main(String args[])
  {
      String str = "54785";
      BigInteger num = new BigInteger(str.getBytes());
      System.out.println("Converted BigInteger to String: " + (new String(num.toByteArray())));
  }
}


Output:
Converted BigInteger to String: 54785


That's all for today. Please mention in the comments if you have any questions related to how to convert BigInteger to String in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry