File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes == and equals in String Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "== and equals in String Class" Watch "== and equals in String Class" New topic

== and equals in String Class

Ram Pathan

Joined: May 18, 2002
Posts: 6
can someone let me know how == and equals work
in the following cases ?
String a1= new String("a")
String a2= new String("a")
Stirng a3=String("a")
String a4=String("a")
Stirng a5="a"
String a6="a"
Will the ans remain same if all the above were
StringBufferclasses instead of string objects ?
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
The == operator compares two variables to determine if they contain the same value. In the case of reference variables, that means that the == operator will determine if each variable contains the same value. That will only return true when both variables contain a reference to the same object.
However, if a class, such as String, overrides the equals method, you can call that method to determine if two objects contain the same values, not to reference variables.
Check out the JLS for more information:
§15.21.3 Reference Equality Operators == and !=

SCJP Tipline, etc.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
There is a trick though with Strings. When a String is allocated with a new:
String s = new String("ABC");
then all the regular rules apply because the String is allocated on the heap. So you will get this behavior:
String a = new String("ABC");
String b = new String("ABC");
System.out.println(a == b) // prints false
However if you declare a String using = instead of new:
String c = "ABC";
the behavior is different because this String is allocated in the literal pool. So you get this behavior:
String c = "ABC";
String d = "ABC";
System.out.println(c == d) // prints true
of course, using .equals() method will find a, b, c, and d all equal.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

just to continue on Thomas' trend -- as a general rule of thumb, always use String abc="abc" rather than the new operator. So you can take advantage of the String Literal Pool.
I agree. Here's the link:
subject: == and equals in String Class
It's not a secret anymore!