Integer.toString(int i) vs String.valueOf(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.