• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString() Vs (String)

 
Sirisha Gajulapalli
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone tell me if there is any difference in using a toString() method vs typeCasting to (String).. for example in the following 2 scenarios wud the result be any different in a specific case?

Scenario 1:
------------
public String getAValue(String aName)
{
return testMap.get("name").toString();
}

Scenario 2:
------------

public String getAValue(String aName)
{
return (String)testMap.get("name");
}
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every class definition inherits the toString() method which allows you to specify a String representation. However, you cannot cast an object to String unless it's runtime type is String.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Casting to string and calling toString() are completely different.

Casting to String just tells the compiler to assume that an object reference that you'd previously typed as something less specific is actually a String. It doesn't actually call any methods or anything like that.

In contrast, toString() calls an overridable method on the object. The default implementation in Object returns some debug information. The version in String just returns the String. Other classes of object do other things.

In your specific example, if your Map actually contains objects that are all Strings, then both pieces of code will actually produce the same result. But don't think that means that casting to String and call toString() are generally the same, because they absolutely aren't.
 
Ryan McGuire
Ranch Hand
Posts: 1057
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:

...
In your specific example, if your Map actually contains objects that are all Strings, then both pieces of code will actually produce the same result. But don't think that means that casting to String and call toString() are generally the same, because they absolutely aren't.


Just to continue that thought...
If your Map actually contains objects that are all, say, Integers, then trying to typecast the return value from getAValue() will throw a ClassCastException. Calling toString(), however, will return a String representation of the retrieved Integer.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should also consider the case when the parameter is not a key:

return testMap.get(aName).toString(); //throws NullPointerException

return (String)testMap.get(aName); //returns null

Is the OP assumes that the map values are Strings?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic