user3537208
user3537208

Reputation: 43

How to compare values between string and BigInteger in java

String str="1234";
String str2="1234";
BigInteger bigInt=new BigInteger("1234");
Object v1=str;
Object v2=str2;
Object v3=bigInt;
System.out.println("Condition1==>>"+v1.equals(v2));
System.out.println("Condition2==>>"+v1.equals(v3));`

Output:

Condition1==>>true

Condition2==>>false

Why the second condition( v1.equals(v3) ) result is false even though the values are same?.What is the difference between two conditions? How to make the second condition result to true?

Upvotes: 0

Views: 2527

Answers (3)

Mordechai
Mordechai

Reputation: 16284

As @RohitJain commented They are not even the same type. Actually the first check in every equals() method is

if(other instanceof ThisType)

In your case:

bigInt.toString().equals(str1)

would return true.

Upvotes: 0

mk.
mk.

Reputation: 11740

You might be confused about how types work. Sometimes, there are certain similar (isomporphic) values between two types. For example, the String "123" and the int 123. Although they look the same, and can be converted from one to the other without loss of information, they aren't actually the same type (and they have no pre-defined automatic conversion in Java), therefore no two values from each type will be equal.

You have to define and perform those conversions yourself. So you'd need to write:

new BigInteger(v1).equals(v3)

Upvotes: 3

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

You need to apply equals on the same class objects. So you need to compare String and String or BigInteger and BigInteger. You can get the String value of your BigInteger and compare it with the String or you need to create a new BigInteger from the String and compare it with the other String.

Upvotes: 0

Related Questions