Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRichard Cowan
375 Pointsrather than use randomNumber + ""; I guessed that we could cast ie (String) randomNumber - Why doesnt this work?
rather than use fact = randomNumber + "";
I used
fact = (String) randomNumber;
This wasnt allowed and I wondered why not?
5 Answers
miguelcastro2
Courses Plus Student 6,573 PointsYou need to use:
Integer.parseInt(myString)
haunguyen
14,985 PointsThis would also work, and easier to understand. But I am not sure about performance penalty.
fact = String.valueOf(randomGenerator.nextInt(5));
Ratik Sharma
32,885 PointsTypecasting an integer to String isn't possible using the (dataType) syntax due to the primitive nature of an integer. Hence we use the following workarounds:
Integer.parseInt(myString);
OR
fact = randomNumber + "";
Adolfo Pitanza
1,458 PointsIn order to get a String value from an Integer you have to use:
fact = Integer.toString(randomNumber);
miguelcastro2 and Ratik (first code-block) explained how to obtain an Integer from a String, and that wasn't what Richard asked ;)
Peter Gordon
2,473 PointsAs above said, you should use
String fact = String.valueOf(randomNumber);
or also
String face = Integer.toString(randomNumber);
I think the first is a better option purely because it's easier to read and understand. I'd also say it is bad style to use the conversion method in the video since the aim is to convert not concatenate.
Juan Mendiola
20,751 PointsJuan Mendiola
20,751 PointsThis is the correct way to convert a String into an integer, but not what the OP was asking. He was asking how to convert an int to a String. In order to avoid confusion it would be good to point that out.