In Java, converting between a String and a BigInteger is a common operation, especially when dealing with large integer values that may not fit into the primitive data types. Java provides convenient methods to perform this conversion. In this blog post, we will explore how to convert a String to a BigInteger and vice versa.
Convert String to BigInteger
To convert a String to a BigInteger, you can use the BigInteger(String) constructor or the BigInteger.valueOf() method.
Using BigInteger(String) constructor:
import java.math.BigInteger;
public class StringToBigIntegerExample {
public static void main(String[] args) {
String numberString = "1234567890123456789012345678901234567890";
BigInteger bigIntegerValue = new BigInteger(numberString);
System.out.println("String: " + numberString);
System.out.println("BigInteger: " + bigIntegerValue);
}
}
Output:
String: 1234567890123456789012345678901234567890
BigInteger: 1234567890123456789012345678901234567890
Using BigInteger.valueOf() method:
import java.math.BigInteger;
public class StringToBigIntegerExample {
public static void main(String[] args) {
String numberString = "987654321098765432109876543210";
BigInteger bigIntegerValue = BigInteger.valueOf(Long.parseLong(numberString));
System.out.println("String: " + numberString);
System.out.println("BigInteger: " + bigIntegerValue);
}
}
Output:
String: 987654321098765432109876543210
BigInteger: 987654321098765432109876543210
Convert BigInteger to String
To convert a BigInteger to a String, you can use the toString() method.
Example:
import java.math.BigInteger;
public class BigIntegerToStringExample {
public static void main(String[] args) {
BigInteger bigIntegerValue = new BigInteger("9999999999999999999999999999999999999999999999");
String numberString = bigIntegerValue.toString();
System.out.println("BigInteger: " + bigIntegerValue);
System.out.println("String: " + numberString);
}
}
Output:
BigInteger: 9999999999999999999999999999999999999999999999
String: 9999999999999999999999999999999999999999999999
Conclusion
In this blog post, we have seen how to convert a String to a BigInteger using the constructor and BigInteger.valueOf() method, and how to convert a BigInteger to a String using the toString() method. These conversions are essential when dealing with large numbers that cannot be handled by primitive data types. By using the BigInteger class, Java allows you to perform arithmetic operations on extremely large integers with ease and accuracy.
Comments
Post a Comment
Leave Comment