## vinay1424

Actually i m doing constructor implementation.But i am new to java, can any tell what going on from line 11 to 14.I am having problem in understanding the bold in line 12 and line 13.Plz help.....

1. public class Animal {
2. String name;
3. Animal(String name) {
4. this.name = name;
5. }
6.
7. Animal() {
8. this(makeRandomName());
9. }
10.
11. static String makeRandomName() {
12. int x = (int) (Math.random() * 5);
13. String name = new String[] {"Fluffy", "Fido",
"Rover", "Spike",
"Gigi"}[x];
14. return name;
15. }
16.
17. public static void main (String [] args) {
18. Animal a = new Animal();
19. System.out.println(a.name);
20. Animal b = new Animal("Zeus");
21. System.out.println(b.name);
22. }
23. }

## Ezzaral 2,714

Well, line 12 is generating a random int from 0-5. So what effect do you think that has in line 13?

## NormR1 563

``int x = (int) (Math.random() * 5);``

Start on the inside and work out. What does the Math.random() method return? Read the API doc
The value returned is multiplied by 5 (*5)
That value is then cast to an int: (int)

Slight correction for the range of values: 0-4
See the API doc about the range of values returned by random for the explanation.

## Akill10 96

Math.random() produces a number where 0 <= x < 1. Therefore, Math.random()*5, produces a number where 0<=x<5. (So it will pick an index from 0 to 4.).

``(int) (Math.random() * 5);``

The (int) Just casts the value of the random number to type int, doing this 'cuts' off any numbers after the decimal, so you are left with a whole number.

## NormR1 563

You should still read the API doc even though most of it has been given to you now

## Ezzaral 2,714

> Slight correction for the range of values: 0-4

Good point. I misstated that.

## Akill10 96

> Slight correction for the range of values: 0-4

Good point. I misstated that.

We forgive you. :)

## vinay1424

I got the point.But in line 13, do they assign the index x to array or something else.Thanks to all for reply.

## stultuske 1,092

in line 13, I think you'll be running into some problems:
you're declaring a regular String object, and you're trying to instantiate it as an array of String objects

## NormR1 563

Notice the [x] at the end.

When in doubt, copy the code into a test program and see what happens.

## stultuske 1,092

Notice the [x] at the end.

hmm .. yeh, how 'd I miss that? :confused:
just ignore my last post