I had come across some strange behaviour while i was looking at some java code.
These are as follows:-

1. here is the first observation
The output of this is false but not

str1 == str2

false.can you tell me why?

String str1 = "shobhit";
		String str2 = new String("shobhit");
		System.out.println("str1 == str2 " + str1 == str2);

2. here goes the second observation

interface abc {
	public  boolean equals(java.lang.Object arg0);
	public void x();
	public String toString();
}

public class xyz implements abc{

	public void x() {
		// TODO Auto-generated method stub
		
	}
	
}

here interface abc has some object class methods.now class xyz has implemented abc and has not implemented the equals and toString methods.still the compiler does not give error but why?
what is the relation b/w interface and object class.
I found this observation when i tried to implement Comparator interface and did not implement equals method and still did not get any compilation errors.
Can you kindly expalin the reasons for the same.

Thanks in advance

equals and toString exist in the Object class (which all Classes implicitly extend), so the class does implement them.

Also, == , when it comes to objects, compares there reference values (i.e. are they the same actual object). It does not compare there content (i.e. do they both contain the value "shobhit". If you wish to compare the content, use str1.equals(str2).

equals and toString exist in the Object class (which all Classes implicitly extend), so the class does implement them.

Also, == , when it comes to objects, compares there reference values (i.e. are they the same actual object). It does not compare there content (i.e. do they both contain the value "shobhit". If you wish to compare the content, use str1.equals(str2).

Thanks for replying,
But another question which comes to my mind is then why the Comparator interface has been provided with equals() method.if anyways every class has got it from Object class and it can override it in the way it want then why it has been provided in Comaparator interfcae.ven if we dont impplement the equals mehtod , it is alwasy there.Pls correct me if i am wrongg.

Also
Thanks for showing concerc to my question but
i am not asking that why it resturned false
i am asking that the following code returned me only 'false' and not 'str1 == str2 false'. can you kindly explain.
String str1 = "shobhit";
String str2 = new String("shobhit");
System.out.println("str1 == str2 " + str1 == str2);

Also if i say this
System.out.println("str1 == str2 " + str1.equals(str2));

then i get the output as 'str1 == str2 true' and not just 'true'.

similarly i shud have got 'str1 == str2 false' and not just 'false'.

Kindly explain.

This article has been dead for over six months. Start a new discussion instead.