Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 948
Nabin Avatar asked Mar 17 '26 18:03

Nabin


1 Answers

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()

like image 137
Mureinik Avatar answered Mar 19 '26 06:03

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!