aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes 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()" Watch ""==" and equals()" New topic
Author

"==" and equals()

Bruno Frascino
Ranch Hand

Joined: Jul 22, 2003
Posts: 55
Ok, I know that operator "==" compares references and equals() values, but, I know too that String is imutable, so why this code on the first example gives 'true' if the others gives 'false'?




--BJCK--
Jay Ashar
Ranch Hand

Joined: Oct 13, 2002
Posts: 208
Bruno,
Strings are stored in a pool of String so when you do
String a = "a";
String b = "a";
variable a creates a new string in a pool and variabe b also points to the same String "a" in that pool and this == gives true for that. When you have something like
String c = new String("a");
Thats means you want to create a whole new string and not reference it to the same string created before, in this case it will give false.
Hope this helps. Someone will correct it if I am wrong, I am giving my certification on 19th of this month.


SCJP 1.4<br />SCWCD 1.3
Davy Kelly
Ranch Hand

Joined: Jan 12, 2004
Posts: 384
correct,
think about a swimming pool, 25 people swimming in it and 5 people are called colin.
say someone puts a call over a tannoy for colin, which one responds?
there is only one name colin but 5 people have that name, this is like the string a = "a"; scenario, so:
string body1 = "Colin";
string body2 = "Colin";
string body3 = "Colin";
string body4 = "Colin";
string body5 = "Colin"; //each person has used the same name.
but string bodynew = new string("Colin"); gets its own address, so it is not in the pool, and therefore bodynew and body1 will not be the same, but body1 and body2 will be.
Hope this helps you see it in a differenet way.
Davy
[ March 10, 2004: Message edited by: Davy Kelly ]

How simple does it have to be???
Bruno Frascino
Ranch Hand

Joined: Jul 22, 2003
Posts: 55
Thanks buddies!
 
 
subject: "==" and equals()