Java Reference
In-Depth Information
This array has seven elements because there are seven initializing string literals between the braces.
Of course, as with arrays storing elements of primitive types, you can create arrays of strings with any
number of dimensions.
You can try out arrays of strings with a small example.
TRY IT OUT: Twinkle, Twinkle, Lucky Star
Let's create a console program to generate your lucky star for the day:
public class LuckyStars {
public static void main(String[] args) {
String[] stars = {
"Robert Redford" , "Marilyn Monroe",
"Boris Karloff" , "Lassie",
"Hopalong Cassidy", "Trigger"
};
System.out.println("Your lucky star for today is "
+ stars[(int)(stars.length*Math.random())]);
}
LuckyStars.java
When you compile and run this program, it outputs your lucky star. For example, I was fortunate enough
to get the following result:
Your lucky star for today is Marilyn Monroe
How It Works
This program creates the array stars of type String[] . The array length is set to however many initial-
izing values appear between the braces in the declaration statement, which is 6 in this case.
You select a random element from the array by creating a random index value within the output statement
with the expression (int)(stars.length*Math.random()) . Multiplying the random number produced
by the method Math.random() by the length of the array, you get a value between 0.0 and 6.0 because
the value returned by random() is between 0.0 and 1.0. The result won't ever be exactly 6.0 because the
value returned by the random() method is strictly less than 1.0, which is just as well because this would
be an illegal index value. The result is then cast to type int and results in a value from 0 to 5, making it
a valid index value for the stars array.
Thus the program selects a random string from the array and displays it, so you should see different out-
put if you execute the program repeatedly.
OPERATIONS ON STRINGS
Search WWH ::




Custom Search