It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes random method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "random method" Watch "random method" New topic

random method

Venkat Ramsimha
Ranch Hand

Joined: Dec 28, 2004
Posts: 127
public class Animal
String name;
Animal(String name)
{ = name;
static String makeRandomName()
int x = (int) (Math.random() * 5);
String name = new String[] {"Fluffy", "Fido","Rover", "Spike","Gigi"}[x];
return name;
public static void main (String [] args)
Animal a = new Animal();
Animal b = new Animal("Zeus");

Hi All,
can anybody explain the random method for the above program

Ranch Hand

Joined: Apr 01, 2005
Posts: 431
While creating an object for the Animal class, if u call the 1-arg constructor which takes the name of the animal then that name will be assigned as the created Animal's (object's) name.

But if u call the no-arg constructor they are selecting a name from a list of 5 names (String[]). They are creating a string with 5 elements and getting one of the elements randomly. To get the random number between 0 and 4 they are using the Math.random() function.

This function will return a value above 0.00 and less than or equal to 0.99. So what ever you get if u multiply by 5 you will get values from 0.05 to 4.95. Since they are casting it with (int) it will truncate the fractional part.

So finally you will get x value as 0<=x>=4. Since they are using x as the index to get the array element, you will get one of the 5 eleemnts from the String array as the name of the animal.

Raghu Shree
Ranch Hand

Joined: Mar 18, 2005
Posts: 143
String name = new String[] {"Fluffy", "Fido","Rover", "Spike","Gigi"}[x]; This line is equalent to
String []nameArray = new String[] {"Fluffy", "Fido","Rover", "Spike","Gigi"};
String name= nameArray[x];

Method makeRandom() retrieve a animal name from array name. [bold]this(name)[/bold] overload the Animal(String name) constructor and prints the animal name.

Raghu J<br />SCJP 1.4<br /> <br />The Wind and waters are always<br />on the side of the ablest navigators.<br /><a href="" target="_blank" rel="nofollow">SCJP Group</a><br /><a href="" target="_blank" rel="nofollow">SCWCD Group</a>
I agree. Here's the link:
subject: random method
It's not a secret anymore!