Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between String.valueOf() and new String()

Tags:

java

string

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) ?

like image 444
user2441441 Avatar asked Feb 23 '14 20:02

user2441441


2 Answers

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.

like image 157
Rachit Avatar answered Sep 17 '22 15:09

Rachit


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);
like image 33
Mr. Polywhirl Avatar answered Sep 18 '22 15:09

Mr. Polywhirl