1

Converting the value to String in java; There are multiple ways of doing it. Just wanted to know what's the difference between each other in the following ways.

strValue.toString()

strValue+""

""+strValue
Exceptional
  • 2,994
  • 1
  • 18
  • 25
  • 1
    What's the type of `strValue`? – Maroun Apr 26 '16 at 07:25
  • 1
    if strValue is already a string, then strValue.ToString() will return itself. – Sebastien Guimmara Apr 26 '16 at 07:25
  • 1
    ""+strValue will internally call strValue.toString(), So technically there is no diff between them. – Ajinkya Patil Apr 26 '16 at 07:25
  • 1
    This is already well explained in answer and question over [HERE ->](http://stackoverflow.com/questions/4105331/how-to-convert-from-int-to-string) and again [HERE](http://stackoverflow.com/questions/3930210/java-int-to-string-integer-tostringi-vs-new-integeri-tostring) – MKJParekh Apr 26 '16 at 07:30

4 Answers4

2

One major difference is how null is handled.

If strValue is null, strValue.toString() will throw a NullPointerException, while the other two options will return the String "null".

Other differences may be observed if strValue is of a boxed numeric type, and you try to concatenate other numeric variables to it.

For example :

If

Integer a = 5;
Integer strValue = 6;

Then

a+strValue+""

would return

"11"

while

a+""+strValue

or

""+a+strValue

would return

"56"
Eran
  • 387,369
  • 54
  • 702
  • 768
2

It depends on java version. Java 7 would act a bit smarter using StringBuilder + append().

Generally, you do not want unnecessary allocations. Use first one.

Maxim G
  • 1,479
  • 1
  • 15
  • 23
2
strValue.toString() 

will return itself, because the toString() implementation of String (I'm guessing strValue is indeed of type String) returns this.

strValue+""

""+strValue

Will result in the same value (strValue) but won't invoke the toString() method

shays10
  • 509
  • 5
  • 18
  • It will. + operator is overwrited for Strings and its based on invoking object's .toString() method which is inherited from *Object* – Laiv Apr 26 '16 at 08:09
2

All Strings contain the same value, try it out:

String strValue = "Hello world"; // not null
String a = strValue.toString();
String b = strValue+"";
String c = ""+strValue;

Measuring its length give all the result 11, because adding an empty String to another one equals the original String itself:

System.out.println(a.length());    
...

Try the equality between these Strings:

System.out.println(a.equals(b));    
System.out.println(b.equals(c)); 
System.out.println(c.equals(a));

They are all true, because these Strings have the same value to be compared. All it in the case the strValue is not null.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183