I have a problem in which I can either use the toString() method to get the String version of an object or typecast it to String. But i want to know which is the more efficient way of doing this?? In terms of memory and cpu utilization which approach would be better?
The cast version : (String) myObject is faster than the myObject.toString()
Actually, as *I* know that myObject.toString() is transformed to ((String) myObject.toString()). So, this in turn requires an extra call to toString() thus, it's a bit slower.
Well, in a normal application you would hardly find the difference as the difference actually accounts when there are very huge say millions of such operrations.
Another point to consider when you use either ways is that if the object you are working on is null then toString() will throw exception. Moreover, you have to be very careful that the object can actually be reffred as String.
If you are using collections, Maps etc. then it is always better to use Generics(JDK5.0).
Er, what?! Casting and toString() are not alternatives to one another.
Casting is something you do to an object reference. If you have a reference of type java.lang.Object, but the object referred-to is really a String, you can cast it to String. However, if the object referred-to is not a String, this will not make it into a String.
The toString() method is entirely different. For a start, a method is something that an object has, not an object reference has. All objects have a toString() method, which will return a String that somehow represents the object. The version of toString() in java.lang.Object is only suitable for debugging purposes, but some objects override toString() to give something more readable.
If you're still confused about this sort of thing, then it's far too early in your Java learning curve to be worrying about what's faster than what. [ March 18, 2008: Message edited by: Peter Chase ]
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.