Listing 7.1 declared the Circle1 class and created objects from the class. You will frequently use the classes in the Java library to develop programs. This section gives some examples of the classes in the Java library.
In Listing 2.5, ShowCurrentTime.java, you learned how to obtain the current time using System.currentTimeMillis() . You used the division and remainder operators to extract the current second, minute, and hour . Java provides a system-independent encapsulation of date and time in the java.util.Date class, as shown in Figure 7.8.
You can use the no-arg constructor in the Date class to create an instance for the current date and time, its getTime() method to return the elapsed time since January 1, 1970, GMT, and its toString method to return the date and time as a string. For example, the following code
java.util.Date date = new jave.util.Date() ; System.out.println( "The elapsed time since Jan 1, 1970 is " + date.getTime() + " milliseconds " ); System.out.println( date.toString() );
displays the output like this:
The elapse time since Jan 1, 1970 is 1100547210284 milliseconds Mon Nov 15 14:33:30 EST 2004
The Date class has another constructor, Date(long elapseTime) , which can be used to construct a Date object for a given time in milliseconds elapsed since January 1, 1970, GMT.
You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0 ). A more useful random number generator is provided in the java.util.Random class, as shown in Figure 7.9.
You can create a Random object for generating random values using its no-arg constructor with the current elapse time as its seed. You can also create a Random object using new Random(seed) with a specified seed. If two Random objects have the same seed, they will generate identical sequences of numbers . For example, the following code creates two Random objects with the same seed, 3 :
Random random1 = new Random( 3 ); System.out.print( "From random1: " ); for ( int i = ; i < 10 ; i++) System.out.print(random1.nextInt( 1000 ) + " " );
Random random2 = new Random( 3 ); System.out.print( "\nFrom random2: " ); for ( int i = ; i < 10 ; i++) System.out.print(random2.nextInt( 1000 ) + " " );
The code generates the same sequence of random int values:
From random1: 734 660 210 581 128 202 549 564 459 961 From random2: 734 660 210 581 128 202 549 564 459 961