• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do the String methods work?

 
Royston Monteiro
Ranch Hand
Posts: 35
Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi folks,
I came accross this question in a Mock test on www.javablackbelt.com


This, when run prints

false
true


I understand that String objects are immutable, so these when you apply these methods to a String object, a new String object is returned.
Above, both the substring() and trim() should return "String".
So, why do they give different results when compared to "String"?
 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since Strings are immutable....performing trim() on " String " would not affect the original string(i.e. " String "). Therefore you are comparing " String " with "String"...which is obviously FALSE.

No. " String ".trim() is equal to "String", so the two strings have the same value. But the trim operation creation a new String object, and since "==" test for object equality -not string equality- the result is false.
[ May 13, 2008: Message edited by: Ulf Dittmer ]
 
Royston Monteiro
Ranch Hand
Posts: 35
Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but what about


Are'nt we getting a brand new String object from this as well?
Also, please look at the following cases:


[ May 13, 2008: Message edited by: Royston Monteiro ]
 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have written the below code and tried out, can anyone please help me out understand this ....



output :

String
false
true
STRING
false

Any one please when why this is happening like this..
[ May 13, 2008: Message edited by: Dinesh Tahiliani ]
 
sachin verma
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go read this it might help you
The SCJP Tip Line Strings, Literally

* 'new' operator ALWAYS creates an object on heap.
* All methods in String class which return a string (toUpperCase(), toLowerCase(), trim() etc.) create the new object on heap, ONLY if required. If not required (say there are no white-spaces to trim), the same instance is returned.

regards
sachin verma
[ May 13, 2008: Message edited by: sachin verma ]
 
Vinayagar Karpagam
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Ideally trim() and substring() should have created new String objects. But substring() has an optimization with it.



As we can see in the code, "this" will be used when there is no need for a String to be created.

Similarly in trim(), "String".trim() == "String" would be true.
[ May 13, 2008: Message edited by: Vinayagar Karpagam ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic