Java Reference
In-Depth Information
We 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 using the method
Math.random()
by the length of the array, we will get a value
between 0.0 and 6.0 since the value returned by
random()
will be between 0.0 and 1.0. The result
won't ever be 6.0 because the value returned by the
random()
method is strictly less than 1.0, which is
just as well as this would be an illegal index value. The result is then cast to an
int
, making it a valid
array index value.
Thus the program selects a random string from the array and displays it.
Operations on Strings
There are many kinds of operations that can be performed on strings, but we can start with one you
have used already, joining strings together, often called
string concatenation
.
Joining Strings
To join two
String
objects to form a single string you use the
+
operator, just as you have been doing
with the argument to the
println()
method in the program examples thus far. The simplest use of
this is to join two strings together:
myString = "The quick brown fox" + " jumps over the lazy dog";
This will join the two strings on the right of the assignment, and store the result in the
String
variable
myString
. The
+
operation generates a completely new
String
object that is separate from the
original
String
objects that are the operands, and this new object is stored in
myString
.
Note that you can also use the
+=
operator to concatenate strings. For example:
String phrase = "Too many";
phrase += " cooks spoil the broth";
After executing these statements the variable
phrase
will refer to the string "
Too
many
cooks
spoil
the
broth
". Note that this does not modify the string "
Too
many
". The string that is referenced by
phrase
after this statement has been executed is a completely new
String
object. This is illustrated
on the following page.