BEHAVIER OF == AND equals() IN STRING:

The equals() is overridden for the String class.
class demo
{
public static void main(String[] args){
String s1="java";
String s2="java";
System.out.println(s1==s2);
}};//output is true because both refers to the same object
== checks the reference. Here what happens first s1 is created in the heap area. When s2 is created it checks the heap for the same character set in the same sequence.When it finds the same string it refers to it without allocating new memory for the same string.So now both s1 and s2 refers to the same memory in the heap.
Check this example
class demo
{
public static void main(String[] args){
String s1="java";
String s2=new String(s1);
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//true
}};
This is because == checks the reference. Now s1 and s2 have two different references. So it returns false.
But the equals method checks the content of the string so it returns true.
Consider this
class demo
{

public static void main(String[] args){
String s1=new String("bhabani");
String s2=new String("bhabani");
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//true
}};

No comments:

Post a Comment