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

References To Strings And ==

Tom Scott
Greenhorn

Joined: Aug 18, 2006
Posts: 21
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
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
btw- thanks for the reply - the extra parentheis achieves the expected result.
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9499
    
    2

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, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023

is the same as the following code:
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9499
    
    2

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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: References To Strings And ==