ContactUs :

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

What is the difference between == and the equals ()?

== is the equality operator which checks weather the  references are equal or not. equals () is used for content comparison.

== is shallow comparison. Means it will use the memory location for comparison rather that the content.
equals() is indepth comparison. It will check the content of the two objects rather that the memory location.
Note : Until and unless we create the new String objects using the “new” operator, they are called the character strings not the String objects and  they all reference to a same memory location and the result will be true, if we compare using the == operator.

public class Test1
{
public static void main(String args[])
{
String s1="venu";
String s2="venu";
if(s1==s2) // same Object reference
System.out.println("H!! first time");
String s3 = new String("ashu");
String s4 = new String("ashu");
if(s3==s4) // different Objects
System.out.println("H!! Second time");
if(s3.equals(s4)) // this will return true as it will check object contents
System.out.println("H!! Third Time");
}
}
Related Posts Plugin for WordPress, Blogger...
Flag Counter