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 trial

Android Build a Simple Android App (2014) Basic Android Programming Generating a Random Number

Richard Cowan
Richard Cowan
375 Points

rather 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

You need to use:

Integer.parseInt(myString)
Juan Mendiola
Juan Mendiola
20,751 Points

This 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.

This would also work, and easier to understand. But I am not sure about performance penalty.

fact = String.valueOf(randomGenerator.nextInt(5));

Ratik Sharma
Ratik Sharma
32,885 Points

Typecasting 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 + "";

In 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
Peter Gordon
2,473 Points

As 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.