Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(String) or .toString()?

Tags:

java

casting

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.

like image 875
Vugluskr Avatar asked Mar 24 '09 06:03

Vugluskr


People also ask

What is the difference between string and toString?

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.

Does toString work on strings?

toString() function can be used with numbers, strings, arrays and objects. toString() function does not take any parameter. toString() function returns a string value.

What is difference between toString and string valueOf () in Java?

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.

Why do we use toString ()?

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.


2 Answers

casting to a String is cheaper since that doesn't require an external function call, just internal type checking.

like image 198
euphoria83 Avatar answered Sep 22 '22 03:09

euphoria83


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.

like image 25
Jon Skeet Avatar answered Sep 25 '22 03:09

Jon Skeet