This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 4 years ago.
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.
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).
Related
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 4 years ago.
I have
Object o = new Object()
o == o.clone(); //I understand this should be false since it's different two arraylist pointing to the same object right?
o.equals(o.clone()) //it's true if it's shallow copy since pointing at the same one
here equals isn't ==, it should be comparing hash code right? since it's object.
source: equals method usage in string and list
but on my notes it says the equal method means == here.
is my notes wrong?
my note says the object class has aclone() method but it has an empty implementation,
and an object of the object class is not allowed to invoke this method because of this reason.
Can someone please explain this b etter? I think I misunderstanding something
== compares object reference - are they the exact same memory reference. equals is a method implemented per class, typically to do more useful comparison (like if two strings contain the same characters, or if two lists contain the same content).
However, the default implementation in Object simply falls back to doing an == comparison, so for instances of that class, there is no difference.
== checks object identity in the context of object references.
Foo f1 = new Foo();
Foo f2 = f1; // Both f1 and f2 refer to the same object.
// f1 == f2 returns true
Foo f3 = new Foo(); // A second instance of Foo is created
// f1 == f3 returns false
Only in the context of primitive data types (boolean, byte, short, int, long, char, float and double) == checks for value.1
The equals method is nothing more than a method to enable objects to compare themselves with other objects. The documentation of equals sets requirements to how the programmer should implement the method, but technically the programmer could do anything he wants.
The implementation of Object.equals(Object) is simply return this == obj).
The equals method should never rely on nor call hashCode(), since it's possible that two objects which are considered unequal according to equals could have the same hash code. The only requirement of hashCode is the other way around: that it must return the same hash code for all object considered equal by means of the equals method.
1 As Andreas already mentioned in the comments – technically == always checks value. This also counts for object references, since object references themselves are values.
This question already has answers here:
two unequal objects with same hashcode
(9 answers)
Closed 6 years ago.
public static void main(String[] args) {
String str1 = "java";
String str2 = str1.intern();
String str3 = new String(str1.intern());
System.out.println("hash1=" + str1.hashCode());
System.out.println("hash2=" + str2.hashCode());
System.out.println("hash3=" + str3.hashCode());
System.out.println("str1==str2==>>" + (str1 == str2));
System.out.println("str1==str3==>>" + (str1 == str3));
}
============================================output===>
hash1=3254818
hash2=3254818
hash3=3254818
str1==str2==>>true
str1==str3==>>false
=================================
Can anyone explain how == returns false even though s1 and s3 having same hashcode?
Despite the comments above, I suspect that you already understand that == determines if two references point to the same object (or are both null), and that you should use equals() if you want to compare two strings for data-equality.
Rather, I think what you're missing is that the hashCode() method corresponds to the equals() method in this respect; it's based on the data in an object, and in fact, it's specified that classes should always implement hashCode() in such a way that if a.equals(b), then a.hashCode() == b.hashCode(). (Of course, there's nothing in the language that enforces this.) The analogue of == that you're looking for is the System.identityHashCode() method.
However, even there it should be noted that System.identityHashCode() does not guarantee that distinct instances will have distinct identity hash codes. (It can't, because it's possible to have more than 232 objects in a JVM at the same time . . . granted, not all JVMs support that; but nothing in the Java language specification forbids it.)
In a correct implementation of equals and hashCode you have the following implications for two objects a and b (that are not null):
if a == b then also a.equals(b)
if a.equals(b) then also a.hashCode() == b.hashCode()
Both implications cannot be reversed in general.
For two Objects the == operator compares their pointer reference. So unless they are actually the exact same object it's never true.
When you do:
String a = "xyz"
while creating the string, the JVM searches in the pool of strings if there already exists a string value xyz, if so 'a' will simply be a reference of that string and no new String object is created.
But if you say:
String a = new String("xyz")
you force JVM to create a new String reference, even if "xyz" is in its pool.
and == compares the references. That's why you are getting the false result.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
String Constant Pool
(5 answers)
Closed 8 years ago.
Consider this piece of code:
String baz = "Hello";
String foo = "Hello";
return foo.equals(baz); // Returns true as expected
return(baz == foo); // Also returns true!
Why does the == operator also return true in this case? It should be comparing the locations of the objects themselves, not their values.
I'm assuming that Java does some sort of internal work and determines these two are of type String (or Integer, etc.) so it implicitly calls the .equals() method.
I'm curious to know exactly how this is done (ie. what goes on in the background), and why this is done, what if I actually wanted to test their location in memory?
return(baz == foo) is also returning true because all literal strings are interned in Java. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
So in short due to use of String intern pool for your case return(baz == foo) is behaving same as return(baz.equals(foo))
Read more about String literals in Java Specs
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am having trouble with a piece of my program, shown here:
String degree1 = degree.getText();
if(degree1 == ""){
degree1 = "Undergrad";}
I want the program to get the text in a textField into a variable, and if that field is blank, to change the contents of the variable to 'Undergrad'
Whenever I test my program, it returns a blank instead of 'Undergrad'
It is because you are using == for string comparison. Use if ("".equals(degree1)) instead.
Operator == compares references, i.e. it returns true for the same object only. If 2 objects are equal but not identical == returns false. This is why class Object contains method equals() that can (and typically should) be overridden by subclasses.
In Java strings are compared using equals method of String class not == operator
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Does Java guarantee that Object.getClass() == Object.getClass()?
I know you're supposed to use equals() in general, but is there any way two Class<?> objects could be equal with equals() but not equal with ==?
edit: I am specifically looking to find out whether two class objects exist such that
Class<?> cl1 = ...
Class<?> cl2 = ...
cl1.equals(cl2) -> true
cl1 == cl2 -> false
This does not seemed to be covered by the possible duplicate question. (which is closely related)
Also it may not be true that the class objects were obtained by someObject.getClass() -- it could be that one was the result of Class.forName(...) and the other from some series of reflective actions like Method.getReturnType().
All objects have both identity (the object's location in memory) and state (the object's data). The == operator always compares identity. The default implementation of equals compares identity as well.
For a fuller explanation:
http://www.javapractices.com/topic/TopicAction.do?Id=17