Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Equality (==), .equals() and String equality

807603Jan 19 2008 — edited Jan 19 2008
Hi,

I'm a first year undergraduate student on Computer Science and am learning Object-Oriented Programming using Java. We've covered the basics in Java (lists, loops and all the constructs) and are now in the second term, learning "Further OOP".

There are, however, a few things I would like clearing up, or to get a better understanding before moving on. I was taught that when checking strings to always use the object's .equals() method, as it will return an accurate result compared to using "==". My question is, in the Java API, the Javadoc comment for .equals() in the String class is as follows:
"Indicates whether some other object is "equal to" this one."
I'm getting slightly confused over this, as I thought "==" checks whether two objects are the same :-s?

When creating a string we have, say:
String example = "Example";
When any other object is created, it's as follows
Iterator it = new Iterator();
We use the "new" keyword. Why is it that when creating a String object, we don't need the "new" keyword?

Also how can "==" return an incorrect result on string equality? Could someone show an example of both and how "==" could return an incorrect result, and why?

I'm quite confused over this so need a comprehensive explaination why .equals() is chosen over "==".

Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 16 2008
Added on Jan 19 2008
4 comments
258 views