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
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
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"
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.
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
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
.