File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes importance of String.valueOf(Object) Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "importance of String.valueOf(Object)" Watch "importance of String.valueOf(Object)" New topic
Author

importance of String.valueOf(Object)

ajse ruku
Ranch Hand

Joined: May 06, 2005
Posts: 192
Hi ,
I have following code.
String test=(String)map.get("x");

Some one suggested me to use
String test=String.valueOf(map.get("x"))

Do we have any advantage of doing this?

regards,
Ajse
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2816
    
    2
Well, what's in the map?

Your first code assumes that the values in the map are all Strings, and so casts to String. If you're right, this is fine. But if any values in teh map are not Strings, the cast fails, and you get an exception.

The second code makes no assumptions about whether the values are Strings or something else. It just calls toString() on any object it finds. It also handles null.

If you're using JDK 5 or later, the map should be declared using generics, and so you should know exactly what type is in it. Then no guessing or casting is necessary. If you have

then later you can use

and there's no need for a cast - the compiler knows that the value is already a String. Or possibly null.

However if you have

then later you should use

Here the only advantage of using valueOf() instead of toString() is that valueOf() handles null without throwing an exception.
ajse ruku
Ranch Hand

Joined: May 06, 2005
Posts: 192
There will be objects in the map.
Mohamed Sanaulla
Bartender

Joined: Sep 08, 2007
Posts: 2946
    
  15

Cast can fail at times. So using valueOf would be safer. But how is the map declared like? If its something like: Map<String,String> then you need to worry about casting or using valueOf.

Update: Ok, I was late this time


Mohamed Sanaulla | My Blog
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: importance of String.valueOf(Object)
 
Similar Threads
Passing null
equals override: 2
Need solution for multiple threads.
Very basic question about hidden if else How this works ??
Using TreeMap class