advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

JavaBoutique: Articles: Tutorials:

Contents
Getting Started
Java Classes and Methods
The Code, Boss...the Code!
A Touch of Class
Packaging up your Code
Running a Java Application
Creating Java Applets
Embedding Applets in your HTML Pages
Adding Interaction
Conclusion

Java Programming
from the Grounds Up

The code, boss...the code!

Figure 1 shows the Java code listing for an application that can generate prime numbers. At the beginning of the code, a class called Primes is declared. This class has a private variable called start that will set the value at which the program starts looking for primes, and a public variable known as count that tracks the number of primes it should find. Line 11 shows that within the class, the method Primes takes a single-integer argument which is used to initialize the private variable start. This is the only way that start can be set, since a private variable is inaccessible outside its class.

FIGURE 1
Primes.java, the source code for a Java application that generates prime numbers.

 1: /**
 2:   Prime number generator
 3:   @author Mark C. Reynolds
 4:   @version 1.0
 5: */
 6:  
 7: class Primes {
 8:   private int start;         // no default
 9:   public int count = 100;    // default value
10: 
11:   Primes(int sta) { // constructor with one arg
12:        start = sta;
13:        }
14:   
15:   private boolean isPrime(int p) {
16:        int i;
17:        for(i=2;i<(p/2);i++) {
18:             if ( i*(p/i) == p ) return(false);
19:             }
20:        return(true);
21:        }
22: 
23:   public void Generate(int arr[]) {  // make 
24:                                         primes
25:        int sta = start;
26:        int cnt = count;
27:        int idx = 0;
28:  
29:        while ( cnt > 0 ) {
30:             if ( isPrime(sta) ) {
31:                  arr[idx++] = sta;
32:                  cnt;
33:                  }
34:             sta++;
35:             }
36:        }
37:   }
38:   
39:   class Mclass {
40:   public static void main(String argv[]) {
41:   
42:   Primes p;
43:   int arrp[];
44:      int len;
45:      int sta = 2;
46:   int cnt = 0;     // dummy default
47:   int i;
48:   
49:      len = argv.length;
50:   if ( len > 0 ) {
51:     sta = Integer.parseInt(argv[0]);
52:     if ( len > 1 ) {
53:       cnt = Integer.parseInt(argv[1]);
54:       }
55:     }
56:   p = new Primes(sta);
57:   if ( len > 1 ) p.count = cnt; // set if user 
58:                                    specified a 
59:                                    count
60:   arrp = new int[p.count];
61:   p.Generate(arrp);
62: 
63:   for(i=1;i<=p.count;i++)
64:        System.out.println("Prime " + i + 
65:                           " is " + arrp[i-1]);:
66:   }
67: }
68:

Line 11 also shows an example of a method (Prime) having the same name as its class (Prime). This special kind of method, called a constructor, permits the programmer to initialize an object in the Primes class before using it. In line 15, the method isPrime takes an integer p and returns a boolean value (set to true or false) indicating whether or not that integer is prime, using brute force procedures. If we had developed a highly sophisticated method of testing for primality, it might be in our commercial interests to retain the rights to that algorithm, so in that spirit the method isPrime has been declared private.

The public method Generate accepts an array name and generates count primes by methodically incrementing up through the integers beginning at the value set for start and testing each one to see if it is prime. Any primes found are loaded into the array passed as the argument to Generate. Since Generate is a public method, it may be called freely by any Java code. Since it is also part of the Primes class, it is permitted to call the private isPrime method. A Java programmer using the Primes class may therefore create a list of primes, but is not permitted to access the function that tests for primality.

This class definition is followed by the definition of the Mclass class. This class contains a single member, a method function known as main. This function is akin to the main() at the heart of C and C++, except that it takes a single argument, an array of elements of type String. Java handles much of its string handling capabilities within its String classes. The section Advanced Java Classes explains the predefined Java classes used in this example in greater detail.

NEXT


Mark Reynolds is a network protocol designer, Java programmer, computer animator, and fanatic mountaineer. He currently consults to Adaptive Optics Associates, a United Technologies company.

Reprinted from Web Developer® magazine, Vol. 2 No.1 Spring 1996 (c) 1996 internet.com Corporation. All rights reserved.


How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Microsoft Visual Studio 2010 Showcase
 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 39
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Windows 7: From Beta to Final Code in One Year
Google Shows Off Chrome OS, Releases Source
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?
Fedora 12 Takes Aim at Linux Networking
Top Supercomputer Nearly Doubles in Speed
Fedora 12 Linux Tackles Virtualization
Apple Gives iPhone Developers App Status Tracker
Novell Sets OpenSUSE 11.2 Free

Creating Custom Export Filters for StarOffice with XSLT
WPF Wonders: Using DataTemplates
Crystal Reports Family Offers Options for Developers
Avaya Aura Session Manager video
Avaya Aura Overview video
Exploring HTML 5's Audio/Video Multimedia Support
Overriding Virtual Functions? Use C++0x Attributes to Avoid Bugs.
Understanding the Cloud Computing Security Vulnerabilities
Cisco and IBM Target a Greener World
Upgrade to Visual Studio 2010 with the Ultimate Offer

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs