Integer.toString(int i) vs String.valueOf(int i)
I am wondering why the method String.valueOf(int i)
exists ? I am using this method to convert int
into String
and just discovered the Integer.toString(int i)
method.
After looking the implementation of these methods I saw that the f开发者_运维百科irst one is calling the second one. As a consequence all my calls to String.valueOf(int i)
involve one more call than directly calling Integer.toString(int i)
In String type we have several method valueOf
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
As we can see those method are capable to resolve all kind of numbers
every implementation of specific method like you have presented: So for integers we have
Integer.toString(int i)
for double
Double.toString(double d)
and so on
In my opinion this is not some historical thing, but it is more useful for a developer to use the method valueOf
from the String class than from the proper type, as it leads to fewer changes for us to make when we want to change the type that we are operating on.
Sample 1:
public String doStuff(int num) {
// Do something with num...
return String.valueOf(num);
}
Sample2:
public String doStuff(int num) {
// Do something with num...
return Integer.toString(num);
}
As we see in sample 2 we have to do two changes, in contrary to sample one.
In my conclusion, using the valueOf
method from String class is more flexible and that's why it is available there.
One huge difference is that if you invoke toString()
in a null object you'll get a NullPointerException
whereas, using String.valueOf()
you may not check for null.
Just two different ways of doing the same thing. It may be a historical reason (can't remember if one came before the other).
The String class provides valueOf methods for all primitive types and Object type so I assume they are convenience methods that can all be accessed through the one class.
NB Profiling results
Average intToString = 5368ms, Average stringValueOf = 5689ms (for 100,000,000 operations)
public class StringIntTest {
public static long intToString () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = Integer.toString(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static long stringValueOf () {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
String j = String.valueOf(i);
}
long finishTime = System.currentTimeMillis();
return finishTime - startTime;
}
public static void main(String[] args) {
long intToStringElapsed = 0;
long stringValueOfElapsed = 0;
for (int i = 0; i < 10; i++) {
intToStringElapsed += intToString();
stringValueOfElapsed+= stringValueOf();
}
System.out.println("Average intToString = "+ (intToStringElapsed /10));
System.out.println("Average stringValueOf = " +(stringValueOfElapsed / 10));
}
}
From the Java sources:
/**
* Returns the string representation of the {@code int} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Integer.toString} method of one argument.
*
* @param i an {@code int}.
* @return a string representation of the {@code int} argument.
* @see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
So they give exactly the same result and one in fact calls the other. String.valueOf
is more flexible if you might change the type later.
If you look at the source code for the String
class, it actually calls Integer.toString()
when you call valueOf()
.
That being said, Integer.toString()
might be a tad faster if the method calls aren't optimized at compile time (which they probably are).
The implementation of String.valueOf()
that you see is the simplest way to meet the contract specified in the API: "The representation is exactly the one returned by the Integer.toString()
method of one argument."
To answer the OPs question, it's simply a helper wrapper to have the other call, and comes down to style choice and that is it. I think there's a lot of misinformation here and the best thing a Java developer can do is look at the implementation for each method, it's one or two clicks away in any IDE. You will clearly see that String.valueOf(int)
is simply calling Integer.toString(int)
for you.
Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object). Only difference is one extra call, which the compiler eliminates to a single call anyway.
So it matters not which you call, other than maybe code-consistency. As to the comments about nulls, it takes a primitive, therefore it can not be null! You will get a compile-time error if you don't initialize the int being passed. So there is no difference in how it handles nulls as they're non-existent in this case.
You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.
Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String
, then various calls to String.valueOf(SomeType)
may be more readable than various SomeType.toString
calls.
my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.
There have no differences between Integer.toString(5) and String.valueOf(5);
because String.valueOf returns:
public static String valueOf(int i) {
return Integer.toString(i);
}
public static String valueOf(float f) {
return Float.toString(f);
}
etc..
Using the method, String.valueOf() you do not have to worry about the data(whether it is int,long,char,char[],boolean,Object), you can just call :
- static String valueOf()
using the only syntax String.valueOf() can whatever you pass as a parameter is converted to String and returned..
Otherwise, if you use Integer.toString(),Float.toString() etc.(i.e. SomeType.toString()) then you will have to check the datatype of parameter that you want to convert into string. So, its better to use String.valueOf() for such convertions.
If you are having an array of object class that contains different values like Integer,Char,Float etc. then by using String.valueOf() method you can convert the elements of such array into String form easily. On contrary, if you want to use SomeType.toString() then at first you will need to know about there their datatype classes(maybe by using "instanceOf" operator) and then only you can proceed for a typecast.
String.valueOf() method when called matches the parameter that is passed(whether its Integer,Char,Float etc.) and by using method overloading calls that "valueOf()" method whose parameter gets matched, and then inside that method their is a direct call to corresponding "toString()" method..
So, we can see how the overhead of checking datatype and then calling corresponding "toString()" method is removed.Only we need is to call String.valueOf() method, not caring about what we want to convert to String.
Conclusion: String.valueOf() method has its importance just at cost of one more call.
精彩评论