| 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>
|
 |
 |
|
|
subject: Trim()
|
|
|