Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

What is the best way to cast something into a String?

+8 votes
Is it just something like this?

int x=5;

(String)x; ?
asked Oct 11, 2016 in CSC 211 (F16) by Brent Pierce (100 points)

2 Answers

+4 votes
 
Best answer

You can't "cast" directly from an int to a String object.  However, you can use various approaches to create a new String object that contains the integer's value as text. 
One approach is:  String strX = "" + x;

answered Oct 11, 2016 by Forrest Stonedahl (3,438 points)
selected Oct 11, 2016 by Brent Pierce
+4 votes
You could do something like this:

int x = 5;

String strX = String.valueOf(x);

answered Oct 11, 2016 by Rachel Cheval (100 points)
...