0

Why below statement return false?

BigInteger bigInteger = new BigInteger("0");
System.out.println((BigInteger.ZERO == bigInteger));

What should i pass in new BigInteger(?) so condition will be true.

arjun kumar
  • 467
  • 5
  • 12
  • 3
    Call `BigInteger.ZERO.equals(bigInteger)`. This is not a primitive. – ernest_k Jun 25 '18 at 17:26
  • I would suspect that `System.out.println((BigInteger.ZERO.equals(bigInteger)));` prints `true`... – achAmháin Jun 25 '18 at 17:26
  • can someone pleaseanswer what BigInteger.Zero is equal to? Is it not a primitive value ? – arjun kumar Jun 25 '18 at 17:32
  • 1
    @arjunkumarmehta no, it is not. Java has eight primitive data types, they are listed [here](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html). `BigInteger` is not one of them. You never call `new ...` on a primitive. – Turing85 Jun 25 '18 at 17:34

1 Answers1

2

By specification, new always creates a new instance (or it fails).

Whatever instance is assigned to BigInteger.ZERO, it's not the one you create in your code with new BigInteger("0").

Since it's not the same instance, and == only returns true if the operands refer to the same instance (provided they are both reference types, which they are in this case), the result is false.


You almost never want to compare objects using a == b or a != B. You should use a.equals(b) or !a.equals(b) instead. (Or Objects.equals, if a might be null).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243