This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes == and equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "== and equals" Watch "== and equals" New topic

== and equals

Srinivasa Rao

Joined: May 09, 2000
Posts: 16
can anybody give me exact difference of == and equals.
~ Srini
sean cee
Ranch Hand

Joined: Oct 24, 2000
Posts: 115
Hi there,
equals compares the actual object.
== compares the memory address
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.

Sean <br />SCJP2, SCJP2p1.4, SCWCD
Srinivasa Rao

Joined: May 09, 2000
Posts: 16
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");

satishind Reddy
Ranch Hand

Joined: Oct 17, 2000
Posts: 33
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

Prasad Ballari
Ranch Hand

Joined: Sep 23, 2000
Posts: 149
I agree with you.
Srinivasa Rao

Joined: May 09, 2000
Posts: 16
Thank you guys ! I got the concept.
It is sorta covered in the JavaRanch Style Guide.
subject: == and equals
It's not a secret anymore!