• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== and equals

 
Srinivasa Rao
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anybody give me exact difference of == and equals.
~ Srini
 
sean cee
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
equals compares the actual object.
== compares the memory address
e.g.
String i =new String("aa");
String ii = new String("aa");
i.equlas(ii) is true 'cos they are "aa"
but i==i is false 'cos their memory address are different.
however for
String i = "aa";
String ii = "aa";
both are true. cos i and ii are pointing at the same thing.
 
Srinivasa Rao
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sean,
Thank you so much.

could you help me why the following code is not giving me any output.
class equality {
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Java");
StringBuffer s2 = new StringBuffer("Java");
String s3 = "Java";
String s4 = new String(s3);
if (s1 == s2)
System.out.println("s1 == s2" );
if (s1.equals(s2))
System.out.println("s1 equals s2");
if (s1.equals(s3))
System.out.println("s1 equals s3");
}
}

~Srini
 
satishind Reddy
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
In your code all three conditions are false.
cond.1 s1 == s2
s1 & s2 are two different object refernces so s1 == s2 returns 'false' but your program handeled only if condition is true then only you are displaying some message.
cond.2 s1.equals(s2)
Actually StringBuffer is not having any equals() method. but it will inherets from 'Object class'.
so Object class equals written true in case of object refernces
values 'x' and 'y' refers to the same object.
i.e(x == y has the value true)
for more details see JLS object equals() method.
cond-3: s1.equals(s3)
In this case one is String literal and another one is String Buffer. for this also second condition apply second condition rule
I think this will help you...
If i am wrong please correct Gures
Regards
Satish

 
Prasad Ballari
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
satishind,
I agree with you.
Prasad
 
Srinivasa Rao
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys ! I got the concept.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic