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 Basic Android Programming Using the Random Class

converting int to String

I'm not sure where my error is ,

RandomTest.java
Random randomGenerator = new Random();
int randomNumber;
randomGenerator.nextInt(10);
String intAsString = "";
intAsString = "" + randomNumber;

2 Answers

This should do the trick

Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(10);
String intAsString = Integer.toString(randomNumber);

This:

intAsString = "" + randomNumber;

works. But it is an unconventional way to do it you should avoid it. Its the "quick and dirty" way :D

Thanks Tobias!! it worked

@Niyamat no no String.valueOf(randomNumber) and Integer.toString(randomNumber) are almost the same (almost). I don't see a performance problem in valueOf(). But I can see one in "" + Integer (in String concatenation).... Of course if you only use this 1-5 times in your program you wont notice it...but if you have to convert Strings ~20 times or more (which can happen easily in big programs as you know) you might notice it.

Niyamat Almass
Niyamat Almass
8,176 Points

Short way to do that-

Random randomGenerator = new Random();

String randomNumber = randomGenerator.nextInt(10) + "";

Yeah but never show these code to an other programmer (or an client who knows some java) ;) it is acceptable but not a good or common way. It is also the slowest way to do it (concatenation is slow in java)

This post explains it quiet good: http://stackoverflow.com/questions/7604379/is-using-int-bad-for-converting-java-ints-to-strings

The common way is either

String intAsString =  String.valueOf(randomNumber)
 String intAsString =  Integer.toString(randomNumber).
Niyamat Almass
Niyamat Almass
8,176 Points

Yes!I know that that way.But I told that it is short way to do that(actually cheating).

Whatever if you take Build a simple weather app course then you will see that Ben Jakuben always use that cheat.Also Ben Deitch in his course "Android activity lifecycle" teach us that way.

So it's a cheat.

There is no problem to use String intAsString = String.valueOf(randomNumber)

If you see any performance problem than you use String intAsString = String.valueOf(randomNumber), it's your choice.

But first take those courses.

But thanks for the link, I learnt something new.