Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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:

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:



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.