-3

While using BigInteger class in Java8, i wrote this piece of code

System.out.println(new BigInteger("1")==BigInteger.ONE);

Ideally it should print true but its output is false. Why its output is false?

Nidhi
  • 147
  • 3
  • 12

3 Answers3

3

== checks if the objects point the same reference, so that if a = b the condition a == b. It's recommended to only do this with primitive types.

To check if the objects' content is the same, use the function equals(Object otherObject). For example:

new BigInteger("1").equals(BigInteger.ONE); 

This will return true, as both objects' content is the same. Using == will return false though, as each object have different references.

Another example would be this:

MyObject object1 = new MyObject(30);
MyObject object2 = object1; //this will make them have the same reference

// This prints true, as they have the same content.
System.out.println(object1.equals(object2));

// This will print true, as they point the same thing, because they have the same reference
System.out.println(object1 == object2);

// We can see they have the same reference because if we edit one's field, 
// the other's one will change too.
object1.number = 10;
System.out.println(object1.number); // prints 10
System.out.println(object2.number); // prints 10 too
eric.m
  • 1,577
  • 10
  • 20
2
new BigInteger("1")==BigInteger.ONE

Can rewrite as

BigInteger bigint =new BigInteger("1");
BigInteger bigint2= BigInteger.ONE;

Now

System.out.println(bigint ==bigint2); //false

Because they points to different references.

== checks the reference. Not the value inside them.

You can try using equals() method to check their equality.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Because you're using == instead of .equals(yourNumberToBeCompared)

You should do:

System.out.println(new BigInteger("1").equals(BigInteger.ONE));
Shine
  • 3,788
  • 1
  • 36
  • 59