| Author |
Some string questions
|
Tom Joiner
Ranch Hand
Joined: Sep 19, 2006
Posts: 47
|
|
1) Does the String.valueOf(Object o) call the objects toString()? If so, why would you ever use it? 2) Why is there no valueOf(StringBuffer buffer) method when there are valueOf for many other data types which can be converted? 3) What would you use String.intern for? Thanks for any ideas
|
SCJP
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26168
|
|
1) According to the JavaDoc, "if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned". A potential use is to avoid having to check for whether you have a null object before the call. 2) StringBuffer extends Object so String.valueOf(Object) already takes care of that case. The other signatures are for non-objects (primitives and arrays) 3) I can't think of any practical uses, but I'm sure there are some.
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
[Tom Joiner]: 3) What would you use String.intern for? To save space. Let's say have a file full of people's names, and you read them all into memory, splitting each into first and last names, and creating a Person object for each one. Many Persons will have the same first name; some may have the same last name. Why create a new String for "Jim" or "Tom" if there's already one in memory? If you call intern() on each String you read, you will discover if there's already an equal String in memory, and share it. (Technically you did already create a new String before calling intern() - but now you can drop it and let GC take care of it. Generally, using intern() saves space, but also takes a little extra time. It may also slow down GC if the Strings you're collecting are things that should be eventually collected. Generally it's pretty rare to see it used in practice, other than for String literals and constants where it's automatic. But there are some applications where it makes perfect sense.
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: Some string questions
|
|
|