Comparing BigIntegers

suggest change

You can compare BigIntegers same as you compare String or other objects in Java.

For example:

BigInteger one = BigInteger.valueOf(1);
BigInteger two = BigInteger.valueOf(2);

if(one.equals(two)){
    System.out.println("Equal");
}
else{
    System.out.println("Not Equal");
}

Output:

Not Equal

Note:

In general, do not use use the == operator to compare BigIntegers

For example, BigIntegers should not be compared in the following way:

if (firstBigInteger == secondBigInteger) {
  // Only checks for reference equality, not content equality!
}

Doing so may lead to unexpected behavior, as the == operator only checks for reference equality. If both BigIntegers contain the same content, but do not refer to the same object, this will fail. Instead, compare BigIntegers using the equals methods, as explained above.

You can also compare your BigInteger to constant values like 0,1,10.

for example:

BigInteger reallyBig = BigInteger.valueOf(1);
if(BigInteger.ONE.equals(reallyBig)){
    //code when they are equal.
}

You can also compare two BigIntegers by using compareTo() method, as following: compareTo() returns 3 values.

BigInteger reallyBig = BigInteger.valueOf(10);
BigInteger reallyBig1 = BigInteger.valueOf(100);

if(reallyBig.compareTo(reallyBig1) == 0){
    //code when both are equal.
}
else if(reallyBig.compareTo(reallyBig1) == 1){
    //code when reallyBig is greater than reallyBig1.
}
else if(reallyBig.compareTo(reallyBig1) == -1){
    //code when reallyBig is less than reallyBig1.
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


BigInteger:
* Comparing BigIntegers

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
58 BigInteger
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap