Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the better approach to convert primitive data type into String

Tags:

java

People also ask

Which method is used to convert data into strings?

toString() method converts int to String. The toString() is the static method of Integer class.

How do you convert a primitive data type?

Converting string to int (or Integer) We can use the Integer. parseInt() to get the corresponding primitive int value of a string or use Integer. valueOf() to get the corresponding value of Integer wrapper class. If the string is not an integer, NumberFormatException will be thrown.

Which method converts a string to a primitive float data type?

We can convert String to float in java using Float. parseFloat() method.


I would use

String.valueOf(...)

You can use the same code for all types, but without the hideous and pointless string concatenation.

Note that it also says exactly what you want - the string value corresponding to the given primitive value. Compare that with the "" + x approach, where you're applying string concatenation even though you have no intention of concatenating anything, and the empty string is irrelevant to you. (It's probably more expensive, but it's the readability hit that I mind more than performance.)


How about String.valueOf()? It's overridden overloaded for all primitive types and delegates to toString() for reference types.


String s = "" + 4;

Is compiled to this code:

StringBuffer _$_helper = new StringBuffer("");
_$_helper.append(Integer.toString(4));
String s = _$_helper.toString();

Obviously that is pretty wastefull. Keep in mind that behind the scene the compiler is always using StringBuffers if you use + in asociation with String's


There's a third one - String.valueOf(..) (which calls Wrapper.toString(..)

Actually the compiler adds Wrapper.toString(..) in these places, so it's the same in terms of bytecode. But ""+x is uglier.


The string-concatenation way creates an extra object (that then gets GCed), that is one reason why it's considered "poorer". Plus it is trickier and less readable, which as Jon Skeet points out is usually a bigger consideration.