I have a method with an Object o
parameter.
In this method, I exactly know there is a String
in "o" which is not null. There is no need to check, or do something else. I have to treat it exactly like a String
object.
Just curious - what is cheaper - cast it to String
, or use Object.toString()
? Or is it same by time-/cpu-/mem- price?
Update: The method accepts Object
because it's the implementation of an interface. There is no way to change the parameter type.
And it can't be null
at all. I just wanted to say that I do not need to check it for null or emptyness. In my case, there is always a nonempty string.
Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert. Tostring() function handles the NULL while the . ToString() method does not and it throws a NULL reference exception.
toString() function can be used with numbers, strings, arrays and objects. toString() function does not take any parameter. toString() function returns a string value.
String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.
casting to a String is cheaper since that doesn't require an external function call, just internal type checking.
I would use a cast. That validates your "knowledge" that it's a string. If for whatever reason you end up with a bug and someone passes in something other than a string, I think it would be better to throw an exception (which a cast will do) than continue to execute with flawed data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With