Android Build a Simple Android App Basic Android Programming Generating a Random Number

Sara Mørk
Sara Mørk
2,325 Points

Why can't I cast an int to a String? (From Building a Simple Android App: Generating a Random Number)

Out of curiosity, I thought it would be interesting to see if the randNum int could be cast into a string- because I thought it would be prettier to look at. For some reason though, casting a type doesn't work in this example.. And I just want to know why? :L

        View.OnClickListener btnClick = new View.OnClickListener() {
            public void onClick(View v) {
                String str = "";

                //select random fact
                Random randGen = new Random();
                int randNum = randGen.nextInt(3);
                str = randNum + "";
               // str = (int)randNum;


2 Answers

Sara Mørk
Sara Mørk
2,325 Points

This makes sense! I didn't know there were different object-type hierarchies in Java :x

I'll give it a shot with .toString();


Actually there is nothing wrong with this part of code, it should be showing a random number from 0 to 2 for each click on the button. but since that's not happening I suppose the reason is " mfunFact.setText(str);" i guess you are typing it with a capital F as a member variables. so it should be mFunFact instead check your member variables.

if that wasn't the reason then show me the full code.

Sara Mørk
Sara Mørk
2,325 Points

Hi Tarek!

Sorry, I was really eager to move on to the next excercise, that I didn't manage to explain my question well. :L

The logic behind the function I've included in my question was taken from the tutorial video (just changed the names of the variables), and at the time of writing, it did the job of outputting a random int between 0 and 2 to the activity.. The only thing I was really wondering is.. Why I can't cast the integer as a string as so;

str = randNum + ""; //why does this work
str = (int)randNum; //and why not this?

Logically, the second line should be doing the same thing. But unfortunately, it throws back an error. The first one does the job, for sure.. But it isn't very pretty! I wanted to know if there was a prettier way to write out this line of code..

str = randNum + "";