Java in 24 Hours, Sams Teach Yourself (Covering Java 9) by Cadenhead Rogers

Java in 24 Hours, Sams Teach Yourself (Covering Java 9) by Cadenhead Rogers

Author:Cadenhead, Rogers [Cadenhead, Rogers]
Language: eng
Format: azw3
ISBN: 9780134663630
Publisher: Pearson Education
Published: 2017-09-08T04:00:00+00:00


FIGURE 15.1

The output of the PrimeFinder application.

Most statements in the application are used to look for prime numbers. The following statements are used to implement threads in this program:

Line 3—The Runnable interface is applied to the PrimeFinder class.

Line 4—A Thread object variable is created with the name go but isn’t assigned a value.

Lines 22–25—If the go object variable has a value of null, which indicates the thread hasn’t been created yet, a new Thread object is created and stored in the variable. The thread is started by calling the thread’s start() method, which causes the run() method of the PrimeFinder class to be called.

Lines 28–44—The run() method looks for a sequence of prime numbers beginning with 2, storing each one in the primes string buffer by calling its append() method.

There’s something unusual in the main() method of this application when a PrimeFinder object is created to begin execution of the program. Here’s the statement:

new PrimeFinder();

Normally you’d expect to see that object assigned to a variable, like so:

Click here to view code image

PrimeFinder frame = new PrimeFinder();

However, because there’s no need to refer to that object again, storing it in a variable is not necessary. Calling new to create the object causes the program to run.

It’s a good programming practice in Java to store objects in variables only when those objects are needed after their creation.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.