What is the difference between String.valueOf() and new String()? When would you use one over the other?
example 1:
public String fun(){
int foo = 55;
return String.valueOf(foo);
}
example 2:
public String fun(){
int foo = 55;
return new String(foo);
}
Update: Yes, the second example doesn't compile as pointed out by others below. I didn't realize it because I have been using new String("something" + foo) and it has worked, as pointed out by fastcodejava. So is there a difference between the two if I use new String("something" + foo) or String.valueOf(foo) ?
The first method takes an integer and converts it to String. However, the second method is just a constructor that creates a new object of type String. It cannot take an integer as argument.
There is no constructor for String
that takes a single integer.
String(byte[] bytes)
String(char[] value)
String(String original)
String(StringBuffer buffer)
String(StringBuilder builder)
You should use:
Integer.toString(foo);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With