Why BigInteger.ONE not equals to new BigInteger("1") in java? [duplicate] - java

This question already has answers here:
Compare two objects with .equals() and == operator
(16 answers)
Closed 7 years ago.
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?

== 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

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.

Because you're using == instead of .equals(yourNumberToBeCompared)
You should do:
System.out.println(new BigInteger("1").equals(BigInteger.ONE));

Related

What is the logic behind == returning false [toString()] when two reference variables are referring to same Object having same hashCode? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
What is the logic behind == returning false when two reference variables are referring to same Object having same hash code values?
public class One {
public static void main(String[] args) {
One o = new One();
One o1 = o;
System.out.println(o.toString());
System.out.println(o1.toString());
System.out.println(o.hashCode());
System.out.println(o1.hashCode());
// Why does it print false ?
System.out.println(o.toString()==o1.toString()); // false
System.out.println(o.hashCode()==o1.hashCode()); // true
System.out.println(o.equals(o1)); // true
System.out.println(o.toString().hashCode()==o.toString().hashCode()); // true
}
}
The line with
System.out.println(o.toString()==o1.toString()); // false
has a toString(). Each toString() creates a new String Object, which are different Objects that have their own memory locations. So the == actually checks the memory addresses between those new String Objects.
Always compare strings with String#equals, not with ==.
== sign checks the memory addresses of objects being compared. In your case, toString() method creates two different String objects stored in two different places. That's why you get false when you try to compare them.
On the other hand, equals() checks the equality of contents of the objects. For your own data types, you should override this method to use it.
hashCode is some sort of a unique identification number for the contents of the objects. That is to say, objects that are equal to each other must return the same hashCode.

Strings == operator compares refrences or not? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public class Test
{
public static void main(String args[])
{
String a="meow";
String b=a+"deal";
String c="meowdeal";
System.out.println(b==c);
}
}
According to me == operators compares refrences . So b==c should print "true"
But it prints "false" . I checked by printing hashcode of "b"and "c" .
Hashcode of both are same
== compares references, but the reference to b and c are different - they're two different String instances although the contain the same content.
If you want to compare the content of both Strings, use equals().
According to me == operators compares refrences .
That is correct. The == operator compares references if both operands are reference types. (It is not correct if either operand is a primitive type ... but that's a different topic.)
So b==c should print "true" But it prints "false" . I checked by printing hashcode of "b"and "c" .
Your reasoning is incorrect.
String a = "meow";
String b = a + "deal";
String c = "meowdeal";
In fact, when that code has finished b and c refer to different string objects that have the same value. In fact, the JLS states that the + operator creates a new string objext ... unless the expression is a constant expression. (And it doesn't qualify as a constant expression in this case, because a is a variable.)
So b == c is false ... BECAUSE == is comparing references, and the references are different.
You should use b.equals(c) for objects and == for primitive types

Java "abc" == "abc" operation [duplicate]

This question already has answers here:
What is the Java string pool and how is "s" different from new String("s")? [duplicate]
(5 answers)
Closed 7 years ago.
When we do:
String a = new String("abc");
String b = new String ("abc");
and do a a == b it returns false because they are 2 diferent objects.
But when we have this:
String c = "abc";
String d = "abc";
and we do a c == d it returns true. Why is that? Should it return false also? Why does the == operator behaves as a .equals() method in this case?
This happens because Java uses a so called Stringpool and tries to reuse old String-Literals to save some memory. But if you say "new String" you always create a new Object based on the Literal. See: here I would suggest you to always use the Objects.equals(a, b) if you want to make sure the objects are equal (or call equal on the Object itself if you're sure it's not null)

How to show !equals in if statement (Java)? [duplicate]

This question already has answers here:
How can I express that two values are not equal to eachother?
(4 answers)
Closed 8 years ago.
How is it possible to show if it's not equal (!=, something like this maybe) in an if statement?
For example:
for (int g = 0; g < doglist.size(); g++){
if(doglist.get(g).equals(name)){
System.out.println("There is no dog with that name: ");
}
}
So in this code I want to print the message if the entry in the list is not equal to name. So instead of equals(name) I'll have to use something different. How is this possible?
You can use the NOT operator ! with appropriate parentheses for clarity (though not strictly required).
if (!(condition))
so in your case....
if(!(doglist.get(g).equals(name)))
You should write
if (!doglist.get(g).equals(name))
About your idea of using !=: For primitive data types, yes, it's correct to test equality using !=. .equals() is for object data types. However, applying != to an object would be testing whether the memory location of the operands is the same, which is not the relevant information. .equals() is what tests for whether the objects are actually equal.
For example, when comparing ints (a primitive type), you would use !=:
int a = 0, b = 1;
if (a != b) doSomething(); //Calls the method
Primitive types do not recognize the .equals() method at all. But if you want to compare Strings (an object type), you would use !<object>.equals():
String s1 = "Hello", s2 = "World";
if (!s1.equals(s2)) doSomething(); //Calls the method
If you used != with an object, it would compile, but likely would not produce the desired output:
String s1 = "Hello!";
String s2 = "Hello!"; //Make a new object with the same data -- contains "Hello!"
if (s1 != s2) doSomething(); //Will run doSomething(), even though s1.equals(s2)

Comparing java Strings with == [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java String.equals versus ==
Is it possible to compare Java Strings using == operator?
Why do I often see, that equals() method is used instead?
Is it because when comparing with literal Strings (like "Hello") using == doesn't imply calling equals()?
there is no custom operator overloading in java. [so you cannot overload it to call equals()]
the equals() ensures you check if 2 Objects are identical,while == checks if this is the exact same object. [so no, using == does not invoke equals()].
== checks if the two objects refer to the same instance of an object, whereas equals() checks whether the two objects are actually equivalent even if they're not the same instance.
No, it's not possible, because with == you compare object references and not the content of the string (for which you need to use equals).
In Java, you cannot overload operators. The == operator does identity equality. The equals(...) method, on the other hand can be be overridden to do type-specific comparisons.
Here's a code snippet to demonstrate:
String a = "abcdef";
String b = a;
String c = new String(a);
println(a == b); // true
println(a.equals(b)); // true
println(a == c); // false
println(a.equals(c)); // true
The one complication is with equals(...) you need to care about null, too. So the correct null-safe idiom is:
(a == null ? b == null : a.equals(b))
This is a loop you don't have to jump through in say C#
To expand on #amit's answer, the == operator should only be used on value types (int, double, etc.) A String is a reference type and should therefore be compared with the .equals() method. Using the == operator on a reference type checks for reference equality in java (meaning both object references are pointing to the same memory location.)
String is a class.So if you try to compare a String with its object that holding a string value you can't use == as it is looking for an object.For comparing the contents of the object you have to use equals
Operator == compares for string object references ,whereas String.equals method checks for both object references + object values . Moreover , String.equals method inturn uses == operator inside its implementation.
From what I know the '==' operator is used to check whether or not to objects are identical.
The presumable compared strings might have the same value(nr of chars etc), but be in fact two totally different objects, thus rendering the comparison false.
== returns true if the memory address is equal on both sides, except for primitive types.
equals should be used on everything that isn't a primitive. classes for the main part.
== operator checks the bit pattern of objects rather than the contents of those objects, but equals function compare the contents of objects.
String str1=new String("abc");
String str2=new String("abc");
System.out.println(str1==str2); will return false because str1 and str2 are different object created with "new" .
System.out.println(str1.equals(str2)) will return true because equals() checks for contents of object.
As amit already said, == checks for being the same object whereas equals() checks for the same content (ok, the basic implementation is equal to == but String overrides this).
Note:
"Hello" == "Hello" //most probably would be true
"Hello".equals( "Hello" ) //will be true
String s1, s2; //initialize with something different than a literal, e.g. loading from a file, both should contain the same string
s1 == s2 //most probably will NOT be true
s1.equals( s2) //will be true, if both contain the same string, e.g. "Hello"
Besides that, the same holds true for object wrappers of primitives, e.g.
Long l1 = 1L;
Long l2 = 1L;
l1 == l2 //will most likely be true for small numbers, since those literals map to cached instances
l1.equals(l2) //will be true
new Long(1) == new Long(1) //will NOT be true
new Long(1).equals(new Long(1)) //will be true

Categories