0
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?

3
  • 5
    Why would you expect String.equals(BigInteger) to ever return true? Those are 2 different types. Commented Mar 16, 2015 at 16:27
  • 2
    Did you read the documentation? for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). Commented Mar 16, 2015 at 16:30
  • @Rohit Jain I have a common method that compares values of two Object types using equals() method.Those two Object types are of different types which are sent as parameters to this method . How to compare the values of different types? Commented Mar 16, 2015 at 16:51

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.