if(" String ".trim() == "String") System.out.println("Equal"); else System.out.println("Not Equal"); Answers 1.the code will compile an print "Equal". 2.the code will compile an print "Not Equal". 3.the code will cause a compiler error prints 3. "Not Equal"?? -Arun
The key to understanding this question is to realize that " String ".trim() returns a new string object that is not shared in the string pool. Although the two string objects have the same content, they are distinct objects.
case 1 prints "Equal". Both case 2 & 3 print "Not Equal" Can somebody please explain why?
The key to understanding this question is to realize that " String ".trim() returns a new string object that is not shared in the string pool. Although the two string objects have the same content, they are distinct objects. Also you can search here for ur question.
Great thanks,<br />Luco Zhao
Joined: Apr 19, 2002
In the first case since there are no leading blanks to remove, a new object is not created.So the answer is "Equal". My question is what happens in the other two cases. As far as I can see both LHS and RHS perform exactly the same operation on the same string literal. So they should share the same String object. Or am I missing something here?
Joined: Mar 26, 2002
The only reason that "String".trim() == "String".trim()returns true is that the trim() function returns the original string object when there is no whitespace to be trimmed. As I understand it, " String ".trim() == " String ".trim() should always return false. Similarly, ("string".toUpperCase() == "string".toUpperCase()) returns false because each of the .toUpperCase() methods returns a new, distinct string. The fact that "String".trim() == "String".trim()returns true is more of an exception to the rule that functions that opperate on strings usually return new string objects that are not shared in the string pool.
Originally posted by Steven Sun: the implementation is so strange.
What is strange about this implementation? It's just an optimization. Think of it this way. When you call a method on a String (many of String's methods function this way), a check is done to see if the original String will be the same as the final String (after the operation has been performed). If they are not, there is no choice but to create a new String and return it. However, if they are the same, why add the overhead of creating a new String - just return the original one. No initialization overhead, no garbage collection overhead - definitely a nice solution. Corey