but according to me answer should be F bcoz string is imutable so it should return new instance of string object.
F is the correct answer, because the == operator is used to check whether two variables refer to the same object. In the instance of the example "String".trim(), "String".replace , etc all refer to different objects, therefore you'll get false. If you wanted to compare the contents of the String variable then use the equals() method. So "String".trim().equals("String".trim()) would give you true.
Originally posted by Al Morrissey: I think your question was wrong. I compiled and run your code and I got this output and it does not match with any of the answers:
true false true false false false
That matches with the answer provided in the original post. We are looking for explanations. Le me try: If you use String literals, then JVM uses the existing Object from heap if it exists there. The trim() returns same string if there is nothing to trim. Otherwise returns a new String. Similaraly replace and replaceAll, return same Object if resulted String an original String are same. Otherwise creates a new Object. Think about the code in light of these 3 sentances and it will clarify the behaviour.
SCEA, SCBCD, SCJP
posted 15 years ago
Can anyone out there tell me from what document that question is from?
Tony Morris Java Q&A (FAQ, Trivia)
posted 15 years ago
Originally posted by George Bolyuba: [qb] Why the result of first trim() should be compared with "String " rather when with "String ".trim() ??? This is wrong.
For the right answer see post by KasiMurugan Ramasamy.
You are right, and I went wrong there. After doing some work on that, i came to know the internals. This was a good one, infact.
I'm going to take SCJPtest and want to know if questions like this one will appear on the exam.
For example do I have to know the fact that replace() will return reference on original object if object will not be changed and replaceAll() will always create a new object? [ July 20, 2005: Message edited by: George Bolyuba ]