Nabin
Nabin

Reputation: 11776

Difference between toString() method and using (+"")

If I have almost any kind of data type (that I can remember), I can do the following:

  1. int x = 5;

    Call function with definition

    function_name(String x){
        //do something
    } 
    

    like this function_name(x+"")//can use (+"") to almost any kind that I can remember

  2. And sometimes use .toString() to some data types or even classes.

I do understand meaning of both. But I am really confused to one thing.

My question: Why do we bother to make toString() method to any class even if it works fine using (+"")? Is it just a way to provide users of our class to use this toString() method or is it faster? Are they alternatives?

Hope I clearify my question. Thank you.

Upvotes: 2

Views: 143

Answers (8)

rupesh jain
rupesh jain

Reputation: 3430

The only difference i see with this approach ""+x is that no of intermediate objects can be more compare to just using toString.

However this might not be always true because the jvm might perform some optimisation to avoid creation of multiple objects.Refer text in bold below:

From jls-15.18.1

The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

The String object is newly created (§12.5) unless the expression is a compile-time constant expression (§15.28).

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

Just for info,this is how it works for primitive types,from docs:

Any type may be converted to type String by string conversion. A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression (§15.9): If T is boolean, then use new Boolean(x). If T is char, then use new Character(x). If T is byte, short, or int, then use new Integer(x). If T is long, then use new Long(x). If T is float, then use new Float(x). If T is double, then use new Double(x). This reference value is then converted to type String by string conversion.

Upvotes: 1

Tulains Córdova
Tulains Córdova

Reputation: 2639

  • When you do +"" on an object you are really calling the toString() method.
  • If you do +"" on an object that hasn't overwritten toString() then the toString() method of the Object class is called. Producing something like MyClass@1948cc8c. That way you know that +"" is of no use without toString().

Upvotes: 2

user207421
user207421

Reputation: 310885

Calling myObject + "" is equivalent to calling String.valueOf(myObject) + "". String.valueOf() in turn is overloaded to do various things dependent on the argument type, including returning "null" for null object arguments, calling argument.toString() for non-null object arguments, or for example Integer.toString(int) for integer arguments.

So your question doesn't make sense. As +"" results in calling toString(), it isn't an alternative to it.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311188

Calling myObject + "" is equivilant to calling myObject.toString() + "", so the + "" is just redundant.

Question: and what about doing it to integer? isn't it casting?

Answer: It's an implicit call to String.valueOf()

Upvotes: 4

BlackJoker
BlackJoker

Reputation: 3191

they are almost the same except one difference: myObject+"" will not throw NPE when myObject is null,but myObject.toString()+"" will.

Upvotes: 1

MeowMeow
MeowMeow

Reputation: 632

toString() may not always print what you want. If you use it on objects* that have not been overridden, it'll print the address of the object. You can overwrite toString() to behave as you need.

Upvotes: 0

Xabster
Xabster

Reputation: 3720

toString()

Is a method declared in class Object which all classes implicitly inherit from. The toString() method there returns the classname followed by @ followed by the hashCode() in a hex string by default.

The Integer class, and many other classes, override this method to provide something useful.

List class does not do this. If you try to

System.out.println(myList + "");

You'll get such an odd looking string. Try it. It is not the "address" of anything like many others suggest.

So in short, if variable+"" works for you, .toString() is already implemented. Explicitly calling .toString() changes nothing, it's what happens anyway. If it doesn't work with var+"" it doesn't work any better with .toString(). You can solve both by implementing (overriding) the .toString() method of the class.

Upvotes: 1

Scott N
Scott N

Reputation: 71

You can't avoid toString (), as that is how java gets the string representation of an object. x+"" calls x.toString().

Upvotes: 0

Related Questions