Author
References To Strings And ==
Tom Scott
Greenhorn
Joined: Aug 18, 2006
Posts: 21
posted Sep 27, 2006 01:25:00
0
Hi All, I was surprised to get the output: false false false I expected to get... true false false ... my reasoning being that s1 and s2 refer to the same string object. Code below: Can someone explain this please? Thanks. Tom
Petrus Pelser
Ranch Hand
Joined: Feb 20, 2006
Posts: 132
Shouldn't it print out: s1 == s2 : false s1 == s3 : false s2 == s3 : false instead of: false false false ??? add parenthesis around the statements as follows: Then everything works as expected. This is because the + operator's precedence is higher than the == operator's . [ September 27, 2006: Message edited by: Petrus Pelser ]
Tom Scott
Greenhorn
Joined: Aug 18, 2006
Posts: 21
posted Sep 27, 2006 01:55:00
0
Ah ha - it does print out as I said however I think the precedence is at the heart of this. Perhaps it evaluates as below...(check new parenthesis I added.) System.out.println(("s1 == s2 : " + m.s1)==m.s2); This would explain the output maybe... Or am I just digging myself in deeper here Cheers. Tom.
Tom Scott
Greenhorn
Joined: Aug 18, 2006
Posts: 21
posted Sep 27, 2006 01:58:00
0
btw- thanks for the reply - the extra parentheis achieves the expected result.
Joe Harry
Ranch Hand
Joined: Sep 26, 2006
Posts: 8795
Hai Tom, As per your code, the operator precedence plays a role. I accept. I'm not understanding to interpret the following from your code snippet, System.out.println("s1 = s2 : " + m1.s1==m1.s2); What happens above??How the + operator makes the output to be false? Please explain. Regards, Jothi Shankar Kumar. S
SCJP 1.4, SCWCD 1.4 - Hints for you , SCBCD Hints - Demnachst , SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
wise owen
Ranch Hand
Joined: Feb 02, 2006
Posts: 2023
posted Sep 27, 2006 06:32:00
0
is the same as the following code:
Joe Harry
Ranch Hand
Joined: Sep 26, 2006
Posts: 8795
Hi Wise Owen, Thank you very much for the explanation and now I understood. Thanks again, Jothi Shankar Kumar. S
Rajesh Kadle
Greenhorn
Joined: Sep 06, 2004
Posts: 26
Should it not print true true true as all the three will be referring to the string constant pool? Can someone explain this. Thanks in advance, -Raj
-Raj
Tom Scott
Greenhorn
Joined: Aug 18, 2006
Posts: 21
posted Sep 28, 2006 14:51:00
0
There is a difference in capitilisation of the letter s. If I change them both to "I am a string" with a small s then all the references are '==' to each other. Cheers, Tom
subject: References To Strings And ==