This question already has answers here:
How to override equals method in Java
(11 answers)
Closed 6 years ago.
public class Employee {
String name;
public Employee(String var){ this.name=var;}
}
public class Main {
public static void main(String[] args){
String s1=new String("joe");
String s2=new String("joe");
Employee e1=new Employee("joe");
Employee e2=new Employee("joe");
system.out.println("When comparing String obj:"+s1.equals(s2)); output:TRUE
system.out.println("When comparing Employee obj:+e1.equals(e2)): output:FALSE
I know we have to override Employee class but Why it is working for String class and I couldn't able to locate the equals override method in Oracle docs for String class also.Please need help !!
In first case you are checking string.
In second case you are checking object of employee.
because two object have different memory address.
more details
String.equals() returns true if the two strings are not null and contain the same sequence of characters, as specified in the documentation by Oracle. This is different from Object.equals() : Object.equals() returns true if two references point to the same object in memory, see https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
The reason the example works as it does is because String overrides the equals method to check the content of the String, whereas the Employee class uses the Object.equals method, which checks memory location.
Different classes have different criteria for what makes 2 objects "equal". Normally, equals() returns true if it is the same Object:
Object a = new Object();
Object b = new Object();
return(a.equals(b));
This will return false, eventhough they are both "Object" classes, they are not the same instance. a.equals(a) will return true.
However, in cases like a String, you can have 2 different instances but String equality is based on the literal characters that make up those Strings:
String a = new String("example");
String b = new String("example");
String c = new String("another");
a.equals(b);
a.equals(c);
These are all different instances of String, but the first equals will return true because they are both "example", but the 2nd will not because "example" isn't "another".
Related
This question already has answers here:
How to override equals method in Java
(11 answers)
Closed 4 years ago.
I have a class named student contains two variables name,no and i have created two objects for the class, now i want to check whether both objects are same or not. I am using .equals() method but i am not getting proper output.
public class Student {
String name;
int no;
Student(String name,int no){
this.name=name;
this.no=no;
}
public static void main(String[] args) {
Student s1 = new Student("abc", 10);
Student s2 = new Student("abc", 10);
System.out.println(s1.equals(s2));
}
}
output: false
You haven't provided an implementation of equals, meaning it will use the default one it inherits from Object, which is the same as: s1 == s2, which returns false because they are not the same object.
You'll need to provide your own implementation.
Take a look at this.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public class HelloWorld{
public static void main(String []args){
String a= "hello";
String ab= a +"John";
String abc = "helloJohn";
System.out.println(ab==abc);
}
}
It prints ab==abc false. Shouldnt it be true..??
Use yourStringVar.equals(anotherString) to check if they contain the same sequence of character, use == to check if they refer to the same object.
In java, String is an object, so two String-objects which have same content will not be equal (because those are different objects), hence abc == ab is not true.
But there are methods to compare the contents of String objects. These are:
abc.equals(ab)
or
abc.compareTo(ab) == 0
You should use for String equals/equalsIgnoreCase. '==' compares objects, NOT VALUES. Because when you make String a = "aa" means you create new object.(like new String("aa")). In java there're equals() and hashCode() methods inherited from Object class, but you may override them.
This question already has answers here:
Java: Why can String equality be proven with ==?
(3 answers)
Closed 8 years ago.
class test {
public static void main(String[] args) {
String a = "Hiabc";
String b = "abc";
String c = "abc";
System.out.println(a.substring(2,5)==b);
System.out.println(b==c);
}
}
output:
false
true
As far as I understand, Java's == look for addresses of the two compared objects. Yet, I don't understand why b==c is true because they must have different addresses. Also, if b==c, then why is a.substring(2,5), which is "abc" == b false?
As far as I understand, Java's == look for addresses of the two compared objects.
Almost correct. Java uses references not addresses, e.g. a reference is strongly typed: See https://softwareengineering.stackexchange.com/questions/141834/how-is-a-java-reference-different-from-a-c-pointer
why b==c is true
The variable b and c are initialized with the same string reference, because they reference the same string literal "abc".
why doesn't substring expression reference the string literal "abc"?
Because the javadoc of substring() says
Returns a new string that is a substring of this string.
So the method does not ensure that a reference to a string from the constant pool is returned. If you want this you have to do
a.substring(2,5).intern()
and than
a.substring(2,5).intern()==b
will be true.
Never compare strings with == in Java.
Use .equal or .equalIgnoreCase methods instead.
The difference between a.substring(2,5) and b is because substring created another String object and it's on a different location than b. It's not about the characters ...
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Actually am testing the functionality of Scanner.
I have a very simple program which has a String variable which contains "abc".Then am reading other String(value "abc") from Scanner using next() method(even i tried with nextLine()).
Then am comparing using the ==, to check whether they are equal according to ==(i know i can compare with equals method which is working as excepted), the strange thing is that it is returning false when i compare using == , even though their hashcode() s are equal and equals() method returning true..
import java.util.Scanner;
public class Tester1234 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String str1="abc";
System.out.println("Eneter abc");
String str2=scanner.next();
System.out.println("str1.hascode()"+str1.hashCode()+"\tstr2.hascode()"+str2.hashCode()+"\tstr2.equals(str1)"+str1.equals(str2));
if(str1==str2)
{
System.out.println("equal");
}
else
{
System.out.println("not equal");
}
}
}
I want to know why it is behaving like this ??
Thanks...!
You are wrong as for the statement that
i know Strings with same content will point to same object in StringPool...
It is true as for literals whitch are hardcoded strings in the code. Compiler creates string pool on compile time and use existing references. But if you are building string on runtime using StringBuilder/StringBuffer (what i belive the Scanner does internally) you are NOT USING entities in string pool, thats why you will get two different objects (references) for the same string content. Workaround for such behaviour is to use intern() however it is performance hit, as interned strings are goint into permgen, and will not be garbage collected.
If we create an String like this...
String str1 = "abc";
object str1 created in String-Pool, and if we create
String str2 = new String("abc");
then, it created in heap, means another new Object.
this is the reason that your condition if(str1==str2) returns false, because these both are different objects.
But there hashcode is equal because both are "abc", so equals method returns true.
you are right that hashcode and equals returning true, hence it will return true for str2.equals(str1).
But str2 is new String and hence it is having difference memory address thats why it will not work for str2==str1. here you are comparing memory address and not content of the string.
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 9 years ago.
The equals method compares whether two object values are equal or not. My question is how it compares the two objects? How can it tell the two objects are equal or not? I want to know based on what it compares the two objects. I am not including the hashCode method.
The default implementation, the one of the class java.lang.Object, simply tests the references are to the same object :
150 public boolean equals(Object obj) {
151 return (this == obj);
152 }
The reference equality operator is described like this in the Java Specification :
At run time, the result of == is true if the operand values are both
null or both refer to the same object or array; otherwise, the result
is false.
This default behavior isn't usually semantically satisfying. For example you can't test equality of big Integer instances using == :
Integer a = new Integer(1000);
Integer b = new Integer(1000);
System.out.println(a==b); // prints false
That's why the method is overridden :
722 public boolean equals(Object obj) {
723 if (obj instanceof Integer) {
724 return value == ((Integer)obj).intValue();
725 }
726 return false;
727 }
which enables this :
System.out.println(a.equals(b)); // prints true
Classes overriding the default behavior should test for semantic equality, based on the equality of identifying fields (usually all of them).
As you seem to know, you should override the hashCode method accordingly.
Consider following example,
public class Employee {
String name;
String passportNumber;
String socialSecurityNumber;
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee();
boolean isEqual = e1.equals(e2); // 1
System.out.println(isEqual);
}
}
In the code at comment //1 it calls inherited equals method from Object class which is simply comparing references of e1 and e2. So it will always give false for each object created by using new keyword.
Following is the method excerpt from Object
public boolean equals(Object obj) {
return (this == obj);
}
For comparing equality check JLS has given equals method to override in our class. It is not final method. JLS doesn't know on what basis programmar wants to make two objects equal. So they gave non-final method to override.
hashcode does not play role to check object's equality. hashcode checks/finds the Bucket where object is available. we use hashcode in hashing technique which is used by some classes like HashMap..
If two object's hashcode are equals that doesn't means two objects are equal.
For two objects, if equals method returns true then hashcode must be same.
You will have to override equals method to decide on which basis you want object e1 and e2 in above code is equal. Is it on the basis of passportNumber or socialSecurityNumber or the combination of passportNumber+socialSecurityNumber?
I want to know based on what it compares the two objects.
Answer is, by default with the help of inherited Object class's equals method it compares two object's reference equality by using == symbol. Code is given above.
logically, equals does not compare objects (however you can do anything with it), it compares values. for object comparison there is '==' operator