• Post Reply Bookmark Topic Watch Topic
  • New Topic

Some string questions  RSS feed

 
Tom Joiner
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37507
552
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!