This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Trim() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Trim()" Watch "Trim()" New topic
Author

Trim()

Sharanya Sharma
Ranch Hand

Joined: Jul 26, 2004
Posts: 54
Hi,

if(" String ".trim() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

Why does this give "Not Equal" as result

and

if("String".toString() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

code results in "Equal"

Thx
Sharanya
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
Sharanya,

In the first example, the trim method produced a new String instance that is equal to " String " with the leading and trailing spaces removed. That new String instance is not the same instance as the one in the String constant pool. In the second example, "String".toString(), the toString method simply returns a reference to itself, and no new instance is created.

I would say that those examples fall into a category that Kathy Sierra refers to as Java Trivia. You don't have to worry about finding anything like that on the real exam. The exam is not intended to test your knowledge of when the String.trim method returns a reference to a new or existing instance of a String.


Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Trim()
 
Similar Threads
Please Answer soon with explanation
please clarify this.....
Doubts in Strings
abhilash mock question
abhilash question