| Author |
Setting strings equal to each other
|
Shaggy Rogers
Greenhorn
Joined: Mar 10, 2006
Posts: 26
|
|
I want to check and see if two strings are equal to each other, and am pretty sure this code: if (title == courseTitle) { aCourse.creditHours = credits; } wont work b/c of the ==. Is there another operator or metod that must be used when checking to see if the two string are equal? thanks.
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
boolean equalStrings = strA.equals(strB); In general, you should always use the (overridden) equals method when comparing objects for "equality." The == is a simple comparison of values (i.e., references in the case of objects). But you should also be aware that Strings are a special case because of a "String pool." For details, see Corey McGlone's article, "Strings, Literally." [ March 16, 2006: Message edited by: marc weber ]
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
ak pillai
author
Ranch Hand
Joined: Feb 11, 2006
Posts: 288
|
|
Try this.
|
java j2ee job interview questions with answers | Learn the core concepts and the key areas
|
 |
Aum Tao
Ranch Hand
Joined: Feb 14, 2006
Posts: 210
|
|
|
What does equals refer to? I think, its an Object class method, and it checks for the hashcode value. Correct me, if something is amiss.
|
SCJP 1.4 85%
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
Originally posted by Aum Tao: What does equals refer to? I think, its an Object class method, and it checks for the hashcode value. Correct me, if something is amiss.
No... In this case, the topic is about strings. The String class overrides the equals() method, with a different implementation. The String classes' implementation actually checks the two strings character by character to see if they are equal by value. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by Aum Tao: What does equals refer to? I think, its an Object class method, and it checks for the hashcode value. Correct me, if something is amiss.
The equals method is defined in the base class Object, which guarantees that all objects have that method. In Object, the method's implementation is a simple comparison of references (as it must be to compare objects). However, the intent is for other classes to override the equals method to provide a comparison that is meaningful to that class. As Henry pointed out above, String has overridden equals to compare Strings on a char by char basis. As described in the API documentation...
The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
|
 |
 |
|
|
subject: Setting strings equal to each other
|
|
|