+ All Categories
Home > Documents > APPLETS AND APPLICATIONS

APPLETS AND APPLICATIONS

Date post: 19-Oct-2021
Category:
Upload: others
View: 7 times
Download: 0 times
Share this document with a friend
31
2 2 APPLETS AND APPLICATIONS KEITH RUTLEDGE M any folks new to Java find the distinctions between applets and applica- tions unsettling and more than a little confusing. I have even had pro- grammers learning Java make the case to me that these distinctions and the differing requirements and capabilities between running in a browser and running in a Java Virtual Machine (JVM) belie the Write Once, Run Anywhere hyperbole about Java. The distinctions, however, are relatively straightforward, and once they are mastered, a programmer can use a reasonable programming tech- nique—discussed in this chapter—to create a Java program that will run in a browser (an applet) or in a JVM (an application). First, I’ll define some terms. An applet is a Java program that runs in a browser. Stated more accurately, a browser provides a context in which an applet can exe- cute. A context is defined pretty much as the dictionary defines it: the circum- stance in which a particular event occurs; the situation. The browser (which is itself a program) can and does invoke methods to initialize, start, stop, and de- stroy the applet program. This chapter discusses how the browser starts the applet 13
Transcript
Page 1: APPLETS AND APPLICATIONS

22APPLETS AND APPLICATIONS

KEITH RUTLEDGE

Many folks new to Java find the distinctions between applets and applica-tions unsettling and more than a little confusing. I have even had pro-

grammers learning Java make the case to me that these distinctions and thediffering requirements and capabilities between running in a browser and runningin a Java Virtual Machine (JVM) belie the Write Once, Run Anywhere hyperboleabout Java. The distinctions, however, are relatively straightforward, and oncethey are mastered, a programmer can use a reasonable programming tech-nique—discussed in this chapter—to create a Java program that will run in abrowser (an applet) or in a JVM (an application).

First, I’ll define some terms. An applet is a Java program that runs in a browser.Stated more accurately, a browser provides a context in which an applet can exe-cute. A context is defined pretty much as the dictionary defines it: the circum-stance in which a particular event occurs; the situation. The browser (which isitself a program) can and does invoke methods to initialize, start, stop, and de-stroy the applet program. This chapter discusses how the browser starts the applet

13

Page 2: APPLETS AND APPLICATIONS

program, finds the resources for the program to run, updates and refreshes theprogram, and, finally, disposes of the program.

Also covered are Java applications and how they compare with applets. Java ap-plications are programs that run in the context of a JVM rather than in a browser.The services provided by the JVM are different from those provided by abrowser. The capabilities afforded to an application, especially I/O capabilities,are different by design; applications have more control over their life cycles fromstart to finish. At the end of the chapter, I present a practical design model forreal-world Java software and position AS/400e as a Java server.

THE STRUCTURE OF AN APPLET

Looking at some code will illustrate how the two types of programs differ in theirarchitecture. Figure 2.1 shows the skeleton of an applet with the four milestonemethods (init, start, stop, and destroy) of an applet’s life cycle in place, but withno code in the methods.

First is the init method. The init method is called by the browser that loads the ap-plet. The browser knows to load the applet because of the applet tag in theHTML document, which the browser loaded first (more about that in a moment).The init method contains (as you might expect from its name) initialization code,plus code that you want to run once and only once for your program. The init

method is guaranteed to precede start and runs only once.

import java.applet.*;

public class AS400Applet extends Applet {

public void init() {add(new java.awt.TextField("Hello World"));// Code runs here to initialize the applet

}

public void start() {

Figure 2.1: An applet has four milestone methods: init, start, stop, and destroy(part 1 of 2).

14

CHAPTER 2: APPLETS AND APPLICATIONS

Page 3: APPLETS AND APPLICATIONS

// Startup Code Goes Here}

public void stop() {// Cleanup Code Goes Here

}

public void destroy() {// Final Cleanup & Unload Code Goes Here

}

}

Figure 2.1: An applet has four milestone methods: init, start, stop, and destroy(part 2 of 2).

The start method runs after the init method and is called by the browser wheneverthe HTML page is revisited. An example of revisiting a page is pressing the Re-load or Refresh key. When a user loads or reloads a page, the browser calls thestart method. Code that you want to run only once for program initializationshould definitely not go here.

I once wrote a program that added a text box to the applet in the start routine.Each time I refreshed the screen, the program dutifully added the text box again.This was not the behavior that I wanted, but it was the behavior that I specifiedby putting add in the start method. It would have been much better to put add inthe init method.

The stop method is called by the browser each time the page is exited. This pre-vents running applets from continuing to use processor resources when they arenot being viewed in the browser. Stop is guaranteed to run prior to the destroy

method and runs one last time if the destroy method is called. The stop method isa good place to temporarily release resources to avoid contention.

The destroy method runs just prior to garbage collection (disposing an object)and always follows the stop method. The destroy method is the method thatshould contain final cleanup code. It should release all open resources, finalizeany necessary states, and release any connections back to the server that servedthe applet.

15

THE STRUCTURE OF AN APPLET

Page 4: APPLETS AND APPLICATIONS

Three other methods that are often used when writing applets are worth mention-ing: paint, repaint, and update. These methods are not shown in Figure 2.1, butapplets that have a dynamic display will use one or more of these three methodsto present a customized graphic, such as animation. The paint, repaint, and update

methods are defined in the base component class, appropriately called Compo-

nent, in the java.awt package. The paint method is the fundamental mechanismthat Java’s Abstract Window Toolkit (AWT) components use to draw themselveson the screen.

Most components, such as buttons, list boxes, and so forth, handle their ownpainting, but if you use components that don’t know how to draw themselves(e.g., Canvas, Panel, or Applet), then your derivation of that class must define apaint method to draw your desired graphic. You don’t have to directly call thepaint function; Java’s AWT task manager automatically invokes paint when thecomponent needs to be redrawn, when the component is first brought on-screen,or when the component is re-exposed or scrolled. Paint is also called by the up-

date method.

On the other hand, the repaint function is designed to be directly called. Whenyou invoke repaint, it basically asks the AWT task manager to call the update

method on the component as soon as possible. The update method then workswith paint to update the appearance of components.

The thing to remember is that, as long as you are using standard graphical com-ponents such as lists, menus, and text fields, you don’t have to worry about cod-ing your own paint, repaint, and update methods. But once you require a customgraphical display, you will have to understand and use these three methods.

RUNNING AN APPLET

How does a browser know to load an applet? There is a tag in HTML called theapplet tag. Figure 2.2 provides the complete syntax of the applet tag in JavaDevelopment Kit (JDK) 1.0.2. JDK 1.1.x adds two new attributes: ARCHIVE andOBJECT. Figure 2.3 shows how the applet tag might look in actual use in anHTML file.

16

CHAPTER 2: APPLETS AND APPLICATIONS

Page 5: APPLETS AND APPLICATIONS

<APPLET CODE="appletClassName"CODEBASE="codebaseURL"ALT="alternateText"NAME="appletInstanceName"WIDTH="pixels"HEIGHT="pixels"ALIGN="alignment"VSPACE="pixels"HSPACE="pixels"><PARAM NAME="appletAttribute1" VALUEPARAM NAME="appletAttribute2" VALUE>alternatehtml

</APPLET>

Figure 2.2: HTML has a tag that allows you to embed a Java applet inside a Web page.

<html>

<head><title>Very Simple Applet HTML Page</title>

</head>

<body>

<appletcode="AS400Applet"align="baseline"width="200"height="100">

</applet>

</body>

</html>

Figure 2.3: The applet tag qualifies the name of the applet and the size and location of theJava window with the Web page.

The following is a brief explanation of the applet tag. For more information onapplet tags and attributes, consult an HTML manual. An applet tag starts with aless-than symbol (<) and the keyword APPLET (<applet). The rest of the attributesfollow in what is actually no particular order (within the applet tag).

17

RUNNING AN APPLET

Page 6: APPLETS AND APPLICATIONS

The CODE attribute specifies the compiled class file that contains the applet. Thiscode is located relative to the code base. The applet name, but not the extension(.class), is given. The CODEBASE is an absolute URL that specifies the locationwhere code and resources will be loaded from. ALT specifies what text to displayif the browser can read and understand applet attributes but can’t run Java code.

WIDTH and HEIGHT are required attributes that give the initial width and height inpixels. NAME is an optional attribute that specifies a name for the applet on thebrowser page, which makes it possible for applets running on the same page to findand communicate with each other. ALIGN is an optional attribute that specifies thealignment of the applet (i.e., left, right, top, middle, or bottom). VSPACE andHSPACE are optional attributes that specify the number of pixels above, below, andbeside the applet. PARAM is a method for specifying an applet-specific parameter.PARAM is how you pass parameters into an applet. Use alternatehtml to provideHTML for browsers that don’t understand the applet tag. A greater-than sign (>)ends the applet attributes, and the applet tag ends with </applet>.

JAVA APPLICATIONS (NO BROWSER REQUIRED)

Now I’ll explain a Java application. Remember that a Java application runs in aJVM rather than in a browser. Figure 2.4 shows an application skeleton.

import java.io.*;

class ApplicationExample {

// class variablespublic static void main(String[] args) {ApplicationExample app = new ApplicationExample();app.nonMain(1.1);System.out.println("Hello from ApplicationExample.main()");

}public void nonMain(double arg) {System.out.println("Hello from ApplicationExample.nonMain()");

}}

Figure 2.4: The main method is the entry point of a Java application; it is automatically calledwhen you invoke the JAVA command and the application’s class name from a command line.

18

CHAPTER 2: APPLETS AND APPLICATIONS

Page 7: APPLETS AND APPLICATIONS

The first line is an IMPORT statement. In this case, the program is importing thejava.io package, which provides file and stream I/O functionality. The second linedeclares a class. Following the class variables (only a comment line in this program)is the main method. The main method is unique to applications. A Java applicationdoes not have the system-defined milestones of init, start, stop, and destroy that anapplet does. When you run a Java application, the system implicitly locates and runsthe main method. The main method must be preceded by three keywords: PUBLIC,STATIC, and VOID. The main method accepts a single argument, which is an array ofstrings that act as the entry parameters list. In addition to the main method, your pro-gram will probably have other methods that do useful tasks.

APPLETS COMPARED WITH APPLICATIONS

Applets and applications differ in their capabilities and behavior. Applets arewell-mannered guests from another system. Applications are resident on the localsystem and behave as though they are at home. Table 2.1 summarizes the differ-ing capabilities and behavior of applets versus applications.

Table 2.1: Applets vs. Applications

Applet Application

Not resident on local system; loadedfrom server at runtime.

Must be installed on local file system.

Loaded by HTML tag. Runs explicitly as parameter to JVM invocation.

Must run within GUI framework orcontext.

Can be GUI or non-GUI.

Has well-defined life-cyclemilestones (init, start, stop, destroy).

Starts at main method.

Flow of execution partially controlledby browser.

Flow of execution completely under programcontrol.

Runs in a “sandbox,” so it is moresecure.

Security is according to the Java security model.

No constructor; uses the init methodto initialize.

Best to provide a constructor; compiler providesdefault constructor if none present.

Socket connections permitted to hostthat served applet.

Socket connections permitted to arbitrary hosts.

Can’t load native code. Access provided to native code.

Audio interface. No audio interface.

19

APPLETS COMPARED WITH APPLICATIONS

Page 8: APPLETS AND APPLICATIONS

It is possible to write a Java program that will run as an applet or an applicationdepending on the calling context (browser or JVM). To do so, you write an appletthat includes a main method. The main method will provide a place for the appletto start running when it is called as an application; the main method will be ig-nored if the Java program is run as an applet. This method must create an appletinstance and place it within a frame. The main method must also invoke the ap-plet life-cycle methods (init, start, stop, and destroy) at the appropriate times tosimulate a browser context.

Examples of this technique can be found in many books on Java, but the one thatI recommend is The Java FAQ by Jonni Kanerva, published by Addison-Wesley(ISBN 0201634562).

JAVA IS STORED IN JARS

Java programs are often loaded across a network. They can be packaged to makemoving them across the network easier and faster. The JAR file format (Java isstored in jars, get it?) creates an archive of multiple Java programs that can bemoved and stored as a single entity. The JAR file format is a general-purposestorage format based on the well-known PKWARE .zip file format. Packagingyour programs into JAR files permits the single movement of a compressed file,rather than multiple movements of uncompressed files. Individual entries in theJAR file can also be digitally signed to authenticate their origin.

A JAR file is created using the JAR utility that came with your JDK 1.1 JVM.Applets created prior to JDK 1.1 can use JAR files by adding the ARCHIVE attrib-ute to their HTML applet tags. The ARCHIVE attribute is archive="jars/jarfile.jar".

The JAR format handles audio and image files as well as class files, works withexisting applets, and is itself written in Java. The JAR format is the preferred wayto package the pieces and resources needed for an applet to run. The syntax forthe JAR command is shown in Figure 2.5.

20

CHAPTER 2: APPLETS AND APPLICATIONS

Page 9: APPLETS AND APPLICATIONS

jar [jar-file] [manifest-file] files ...Options:-c create new archive-t list table of contents for archive-x extract named (or all) files from archive-v generate verbose output on standard error-f specify archive file name-m include manifest information from specified manifest file-0 store only; use no ZIP compression-M Do not create a manifest file for the entries

Figure 2.5: The JAR command is similar to the Zip utility in that it has options that allow youto create a file that contains compressed files and then to decompress those files.

WHICH TYPE IS RIGHT FOR YOU?Which type of Java program will you write? That’s a philosophical, an architec-tural, and a program-design question. If you want to let someone else managemuch of the user interface services, if you don’t want or need your programs toaccess the executing machine’s file system, and if you want everything to runfrom a central code base, then applets could be a good choice. If you require ac-cess to local file systems and multiple arbitrary hosts in your network, or if youneed to run in batch, then applications are probably the way to go.

Most of the noise so far in Java has been about client applets. Web programmingin Java delivers client applets that interact with the user and maybe the host thatserved them. Applets can be very useful for graphical tasks or for front-end taskssuch as a data entry screen. Applets are in wide use today and will most likely bepart of any significant Java code portfolio. Applets are the mechanism for ex-tending an existing enterprise application to the Web.

Applications can do heavier lifting than applets. Applications have access to thelocal file system, have access to native code (through the Java Native Interface,or JNI), and can run without a GUI (making them well suited for unattendedtasks such as batch execution). Also—and this is not yet widely appreciated—be-cause applications run in a JVM instead of a browser, they can be used to handlelarger computing tasks. JVMs run on both client machines (e.g., Windows 95)and server machines (e.g., AS/400e). A JVM running on an AS/400e with 256MB of memory (or more) and 8 GB of disk (or more) can run a much larger

21

WHICH TYPE IS RIGHT FOR YOU?

Page 10: APPLETS AND APPLICATIONS

program than a browser running on a Windows 95 machine with 16 MB or 32MB of memory.

JAVA AND A REALISTIC DESIGN MODEL

Most software implementations done in Java will use both applets and applica-tions. Applets will provide access across the network to the functionality con-tained in the software. Applications will be used for client software where theinfrastructure is under control, supports Java application requirements, and willbe used for the other tiers of an n-tier client/server architecture. Java softwarewill be done as a multiple-tier (2, 3, or n) client/server system.

Many people use the term network-centric to describe the architecture of soft-ware written using Java. That term probably is better; it avoids all those tiresomediscussions of client/server models.

I think that software written in Java will, over time, arrive at a four-layer (or tier)model. I deliberately avoid the terms client and server here to avoid mapping thisrelatively simple conceptual architecture onto an existing model; I feel that thisapproach is simpler.

In the four-layer model, there will be a user interface layer, which will use Javaapplets or applications. There will be a request broker layer, the function ofwhich is to manage (prioritize, schedule, and monitor) requests from the varioususers in the network to the various providers in the network. There will be a busi-ness-rule layer. The business-rule layer will contain “debits equal credits” kindsof logic and will provide business functionality. And, finally, there will be a datalayer. The data layer will provide data management and integrity functionality.

Already in use today, this is a straightforward model against which to designsoftware. I feel compelled to acknowledge that, in any real system, a lot of func-tionality crosses these conceptual, arbitrary layer borders. So, let the consultantsargue about whether this is a 2-, 3-, or n-tier model. The proposed model is an ef-fective software design and implementation model.

22

CHAPTER 2: APPLETS AND APPLICATIONS

Page 11: APPLETS AND APPLICATIONS

In the four-layer model, applets are used only at the user interface layer and notfor all of that layer. The request broker, business-rule, and data layers are all Javaapplications. These applications are all Java server applications. Based on analy-sis of the functional content of large software systems, server-side Java will bemuch larger than client-side Java. Server-side Java will also encapsulate muchmore business value.

WHAT ABOUT AS/400E?Where does the AS/400e fit in this brave new Java world? It runs the request bro-ker(s), the business-rule layer, and the data layer. It also serves the applets thatprovide network access through the user interface layer. In addition, it can pro-vide local file storage for the clients that use applications for the user interfacelayer. AS/400e is well positioned to be a Java server as the business content ofJava software continues to increase.

AS/400e has all the components necessary to be a Java server. It has a JVM thatis suited to large computing tasks and large numbers of users. It has a range ofoptions for HTTP serving (HTTP or Internet serving is a prerequisite to servingapplets). It has good componentry (the AS/400e Toolbox for Java) for providingaccess to AS/400e resources. It has excellent cooperative development tools(VisualAge for Java for AS/400e or Borland’s JBuilder). It has good TCP/IP net-work support. And it has the necessary security tools (e.g., AS/400e object-basedsecurity, firewall support, and encryption support for the network).

23

WHAT ABOUT AS/400E?

Page 12: APPLETS AND APPLICATIONS
Page 13: APPLETS AND APPLICATIONS

33AN AS/400 PROGRAMMER’S

FIRST LOOK AT JAVA

RICHARD SHALER

By now, most of you have probably read at least one article about Java, soyou don’t need a long discussion about why there is so much interest in the

subject. The primary focus of this chapter is to get right into the language andstart teaching you how to program with Java. This chapter certainly isn’t a com-plete tutorial, but there is lots of additional information as you get into other sec-tions of the book. What I’m trying to present here is a condensed introduction toJava from an AS/400 perspective.

To get the most out of this chapter, you should key in the sample Java code andcompile it. Anyone can download Sun Microsystems’ Java Development Kit(JDK) off the Web (java.sun.com). Many other more sophisticated integratedJava development environments (most of them with visual development tools),such as IBM’s VisualAge for Java, Symantec’s Visual Café, and Borland’sJBuilder, are available for less than $100.

25

Page 14: APPLETS AND APPLICATIONS

WHY JAVA?There are many reasons why Java is being promoted as the language of networkcomputing—the Holy Grail of programming languages. Here are a few of themore important reasons:

Object-oriented—Java is an object-oriented (OO) language that improves reli-ability and reusability of code. Many computer languages today, such as C++ andSmalltalk, are OO. Even legacy languages such as COBOL are evolving intoOO-capable languages. One of the benefits of Java is that it was designed fromthe ground floor as an OO language. Unlike C++, Java makes it more difficult toignore OO rules.

Small executables—Java generates very small executables, which means that itis well suited to an environment where application code needs to be downloadedfrom the server to a client machine.

Security—Java programs execute within the Java Virtual Machine (JVM) in-stead of the native mode of the client operating system. Java cannot corruptmemory outside its process space. For example, a Java program that runs in aWeb browser cannot access anything that the client machine doesn’t grant it ac-cess to. This kind of Java program (applet) can’t even perform file I/O.

Machine-independent—Because Java code runs through a JVM and JVMs areavailable on most computers (through browsers or natively through the operatingsystem) and network stations, there’s no need for the program to be machine-dependent. You write your Java code once, for all platforms.

Simple—Although similar to C++, Java is simpler. Many of the complexities ofC++ have been removed. For example, in Java, you don’t need to be concernedabout memory allocation and deallocation, and you don’t have to work withpointers. The Java byte codes allow for portability, but the downside is that Javaprograms are interpreted. Of course, interpreted code runs slower than the nativeexecutable code. To improve performance, there is a technique known asJust-In-Time (JIT) compilation. The JIT method works like this: When a Java

26

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 15: APPLETS AND APPLICATIONS

program is first received by a client computer, the JIT compiler converts the Javabyte code into a native program.

HOW JAVA WORKS

When you compile a Java program, the compiler does not create an executableprogram for the particular architecture of the machine on which you’re compil-ing. Instead, the Java compiler creates what is known as Java byte codes. Thesebyte codes are instructions that a JVM understands and executes. JVM is avail-able in browsers such as Netscape Navigator (2.0 and 3.0) and Microsoft’sInternet Explorer 3.0. Some of the major computer operating systems such asOS/2 include a JVM in the operating system.

There are two types of Java programs: applets and applications. Java applets areprograms written to run on a Web browser. Applets are actually launched froman HTML document through special embedded HTML statements. The HTMLsource code in Figure 3.1 is an example of how you might embed a Java appletwithin an HTML document.

<APPLETCODE="JavaApplet.class"WIDTH=250HEIGHT=100>

</APPLET>

Figure 3.1: The applet tag qualifies the name of the applet and the size and location of theJava window with the Web page.

Java applications, unlike Java applets, do not run from a Web browser; applica-tions run on the computer like a native program. For example, the current JVMavailable for the AS/400 runs Java applications within OS/400, not a Webbrowser. However, you will need a JVM to execute the application. You can exe-cute the Java application from a command line or through the Java developmentsystem you are using.

27

HOW JAVA WORKS

Page 16: APPLETS AND APPLICATIONS

JAVA STATEMENTS

A Java statement can be a comment, a declaration, a conditional statement, or ablock. Most Java statements end with a semicolon (;).

Comments

Comment statements do not end with a semicolon. There are three types ofcomments.

One: A double slash (//) comment continues from the two slashes to the end ofthe statement. These types of comments are usually just one line long. In the fol-lowing example, the executable Java statement is preceded by a comment:

// add 1 to integer variable xx = x + 1;

In the next example, the comment is appended to the executable Java statement.Notice that the executable portion of the statement ends with a semicolon.

x = x + 1; // add 1 to integer variable x

Two: For multiple lines of comments or blocks of comments, use the slash aster-isk (/*) and asterisk slash (*/) combination. The slash asterisk comment continuesuntil an asterisk slash is encountered. This type of comment makes it much easierto deal with blocks of comment statements.

/* This is a block of comment statements that continues lineafter lineafter lineuntil here */

Three: The final type of comment allows comments to be extracted from a pro-gram and converted into an HTML file, producing professional-looking docu-mentation of your program. For this type of comment, start with a slash doubleasterisk (/**) and end with an asterisk slash (*/). Each separate line between thebeginning and the end must begin with an asterisk. These comments are normally

28

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 17: APPLETS AND APPLICATIONS

used to document classes and methods. A whole chapter could be written aboutthese special comments. To find out more, refer to the Javadoc utility that comeswith the Sun JDK.

Declaration Statements

Declaration statements, as the name implies, declare something such as a variableor a class. For example, the following declaration states, “I declare integer vari-able x and initialize it to the value of 1”:

int x = 1;

In this statement, I add 1 to variable x and assign the value to x:

x = x + 1;

As in RPG, variables in Java can be defined on the fly; they don’t have to be de-fined at the beginning of the program. In the following example, the statementperforms an assignment to variable x and defines x at the same time:

int x = x + 1;

Conditional Statements

Conditional statements are used for program flow control. There are basicallyfour conditional statements: the IF statement, the WHILE loop (which can alsofunction as a Do Until), the FOR loop, and the SWITCH statement. Here is thestructure of the IF statement:

if (boolean expression) {// statement here

} else {// statements here

}

And here is an example of the IF statement:

29

JAVA STATEMENTS

Page 18: APPLETS AND APPLICATIONS

if(amount >= 100.00) {discount = .10;

} else {discount = .00;

}

The WHILE loop is similar to the DOW or DOWxx loop in RPG. The statement orblock following the while is executed while the condition in the while expressionis true. There are actually two forms of the WHILE loop. The first form is asfollows:

while (boolean expression) {// statements here

}

Here is an example of the WHILE statement:

while (ctr <100) {ctr = ctr + 1;

}

The second form of the WHILE loop (a.k.a. the DO statement) is similar to an RPGDOU or DOUxx loop. The block of code is always executed at least once. Theloop continues until the while condition is not true.

Do {// statements here

} while (boolean expression)

Here is an example of the DO statement:

Do {ctr++;

} while (ctr < 100)

The FOR loop is probably the most popular form of loop structure. You will seethis used often in Java. There is no equivalent of a FOR loop in RPG.

30

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 19: APPLETS AND APPLICATIONS

for (expression1; boolean_expression; expression3) {// statements here

}

Here is how the FOR statement works:

1. expression1 is evaluated.

2. boolean_expression is evaluated.

a. If true, the body of the FOR loop is executed.

b. If false, control passes to the statement after the FOR statement (orbeyond the closing brace if the statement is a block statement).

3. expression3 is evaluated.

4. Go to step 2.

In the following example of a FOR loop, an array is being loaded with the num-bers 0 through 9:

for (ctr = 0; ctr < 10; ctr++) {numbers[ctr] = ctr;

}

The SWITCH statement is used when you want to select one of many alternatives.For example, you could use a SWITCH statement to process the selected option ofa menu of options. The SWITCH statement is similar to the RPGSELECT/WHEN/ENDSL operations. Figure 3.2 shows an example.

switch(expr){case constant_integer_expression1:// statements herebreak;

case constant_integer_expression2:// statements herebreak;

default;// statements here

}

Figure 3.2: Java’s SWITCH statement is similar to RPG’s SELECT statement.

31

JAVA STATEMENTS

Page 20: APPLETS AND APPLICATIONS

Figure 3.3 contains an example of a SWITCH statement used to process three pos-sible options.

switch(option){case 1:packingSlip.print();break;

case 2:invoice.print( );break;

case 3:label.print();break;

default;System.out.println("Invalid option selected.");

}

Figure 3.3: A behavior of Java’s SWITCH statement that you need to be aware of is thatwithout BREAK statements, control logic continues to drop through the CASE clauses.

Statement BlocksYou might have noticed the braces ({}) contained within the group of statementsin Figure 3.3. Because I wanted to condition more than one statement with theconditional SWITCH statement, I formed a statement block by surrounding thegroup of statements with opening and closing braces. (Java statement blocks donot end with a semicolon.) Often, blocks are associated with conditional state-ments. For example, in the Java code in Figure 3.4, the first block of code exe-cutes if TotalSales is greater than or equal to $100,000; otherwise, the secondblock of code executes.

if ( TotalSales >= 100000.00)

VacationDays = VacationDays + 2;Bonus = 200.00;

}else{VacationDays = VacationDays + 1;Bonus = 0.00;

}

Figure 3.4: Blocks of code within IF/THEN/ELSE clauses are demarcated with braces.

32

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 21: APPLETS AND APPLICATIONS

The two statement blocks in Figure 3.4, like all statement blocks in Java, areidentified by the opening and clos-ing braces. For RPG programmers,it might be helpful to compare thepreceding example to an RPGequivalent: the IF, ELSE, and ENDIF

operators.

DATA TYPES

The size of each variable type is anintrinsic part of the language. Nomatter what platform you are run-ning Java on, the size of each datatype is the same. This greatly im-proves the language’s portability.There are eight variable types, asshown in Figure 3.5.

DECLARING VARIABLES

All variables must be declared before they are used. Java is case-sensitive, so thevariable name anum is different from the variable ANUM. If you don’t initialize avariable, a default value is assigned, as shown in Figure 3.5. You must declarethe variable type when you define a variable. Figure 3.6 shows several examples.

// declare a variable named x as type integerint x;

// declare variable name ch as character variablechar ch;

// declare an integer variable named y and initialize it to 1int y = 1;

// declare a character variable named ch and initialize it to Achar ch = 'A';

Figure 3.6: Variables can be declared and initialized with the same statement.

33

DATA TYPES

Figure 3.5: Java has eight basic data types.

Page 22: APPLETS AND APPLICATIONS

If you want to define more than one variable of the same type, you can declarethem all in one statement. For example:

// define three variables of type integerint x, y, z;

ARITHMETIC OPERATORS

Arithmetic operators for add, subtract, multiply, and divide are, respectively, theplus sign (+), the hyphen (-), the asterisk (*), and the slash (/). Here are some ex-amples of arithmetic operators:

linetotal = (qty * price) - discount;percent = amounbotal + amount;

The mod (or remainder) operation is also supported through the percent symbol(%). For example, the following statement will assign the value of 2 to variable x:

x = 12 % 5;

There is no symbol for exponentiation; you must use the Java pow method of theMath class (Math.pow). (For an example of raising a quantity to a power, see Fig-ure 3.11.)

UNARY OPERATORS

There are four unary operators in Java: negation (-), increment (++), decrement(—), and bitwise complement (~). The negation operator is simple. If you want tonegate a value, you simply precede it with a – (hyphen).

The increment and decrement operators can be used two different ways: pre-increment or postincrement (or predecrement and postdecrement). For example,

ctr = 1;totalctr = ++ctr; // totalctr equals 2

34

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 23: APPLETS AND APPLICATIONS

Because the unary increment operator precedes the variable ctr, ctr is incre-mented before the value is assigned to totalctr. If ctr was equal to 1 prior to thisoperation, totalctr would equal 2. You can postincrement a variable by followingthe variable with the unary increment operator.

ctr = 1;totalctr = ctr++; // totalctr equals 1

In this example (totalctr = ctr++), if ctr equals 1 before the operation, totalctr

would be equal to 1. (Variable ctr is not incremented until after the assignment isperformed.)

The bitwise complement operator works on bit patterns. Working on bit patternsis beyond an introductory chapter such as this. For further information on bit pat-terns, see your Java development systems help text.

RELATIONAL AND BOOLEAN OPERATORS

Although the equal sign (=) is used for assignment in Java code, double equalsigns (==) are used to compare for an equal relationship. Use an exclamationpoint and an equal sign (!=) for not equal.

Use a less-than symbol (<) for less than, a greater-than symbol (>) for greaterthan, a less-than symbol and an equal sign (<=) for less than or equal, and agreater-than symbol and an equal sign (>=) for greater than or equal. Java, like C,uses two ampersands (&&) for the AND operator and two pipes (||) for the OR

operator.

ARRAYS

Arrays are basically defined by specifying the type of data they will contain, thename of the array, and then the number of elements. For example, in the follow-ing declaration, I am defining an integer array called IntArray with 10 elements:

int[] IntArray = new int[10];

35

RELATIONAL AND BOOLEAN OPERATORS

Page 24: APPLETS AND APPLICATIONS

An array is actually an object, and you must use the NEW operator to explicitlycreate it. An array also can be defined with the brackets after the array name(e.g., int IntArray[] = new int[10];), but I’ve read that placing the brackets before thearray name is more common.

You reference the first element of an array in Java with a 0, the second elementwith a 1, and so on. For example, the following statement prints the third elementof the array:

System.out.println("The third element of IntArray = " + IntArray[2]);

In this example, the plus sign is a concatenation symbol. Here I am concatenatingthe value in element three of IntArray to the character string preceding the plussign. Here’s a snippet of code that loads an integer array of 10 elements with thenumbers 0 through 9:

for (int = 0; i < 10; i++)IntArray[I] = i;

STRINGS

String is not a data type in Java; it is a class called String. Strings are simply a se-quence of characters. Declare a string as follows:

String CoName;Declare and initialize a string like this.String CoName = "Midrange Computing";

You can concatenate a string with the plus sign. In the following example, I con-catenate a blank to FirstName and then concatenate the LastName.

FullName = FirstName + ' ' + LastName;

Unlike in a Java array, you cannot change a specific character within a string. Forexample, I can’t change the spelling of “Midranje” to “Midrange” by replacingthe “j” with a “g.” However, I can modify the string by concatenating the

36

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 25: APPLETS AND APPLICATIONS

characters I want to replace with the substring of the portion of the string I wantto keep. Assuming the name of my string variable is Name, to change the stringMidranje to Midrange, I can use the following statement:

Name = Name.substring(0,5) + "ge";

In Java, you invoke an objects method with the .method notation. In the example,substring is a method of object Name. The first argument of the substring method(0) references the first position of the substring; the second argument (5) speci-fies the ending position of the substring. In this case, the substring value is“Midran.” Notice that the first position of the substring is referenced with a 0, nota 1, and the ending position is referenced with a 5, not a 6. As with Java arrays,you reference relative positions of strings starting with 0.

CONSTANTS

In Java, you define constants for the entire class; you cannot define a local con-stant for a specific function (method) of the class. So, it stands to reason that youdefine constants prior to the main function. Use static final to declare a constant,as illustrated in the example shown in Figure 3.7.

class test{static final double pie = 3.14159265;public static void main(String[] args){System.out.println("Pie = " + pie);

}}

Figure 3.7: A Java application’s main method is the entry point to the class.

In this example, the scope of pie is to this class only. To declare the pie constantin Figure 3.7 as global, precede static final with public (i.e., public static final).

37

CONSTANTS

Page 26: APPLETS AND APPLICATIONS

LITERALS

A literal is a symbol or quantity that is itself the data, rather than a reference tothe data as with a variable. Java contains five different types of literals:

■ Integer.■ Numeric containing a decimal point or exponent.■ Boolean.■ Character.■ Special character.

Integer literals by default are 32-bit (4 byte) signed decimal numbers similar toan int variable. Any integers greater than 2,147,483,647 are assumed to be longintegers. You can force a number smaller than this to be long by ending with an“l” or “L.” To force 31 to be a long integer, specify “31L.”

Any numeric literal that contains a decimal point or an exponent is assumed to bea floating-point number, type double. An “f” or “F” can be appended to the endof a literal to force it to be a floating-point number, type float. A “d” or “D” canbe appended to the end of a literal to force it to be a floating-point number, typedouble.

Literals can be expressed in octal by preceding the number with a 0 (zero). Forexample, 037 would be an octal literal. Literals also can be expressed in hexadec-imal by preceding the number with a “0x” or “0X.” Java uses two Boolean liter-als: true and false. Boolean literals do not need to be defined. You simply specifyone or the other literal. For example:

while(true) {//statements here

}

Character literals must be enclosed in single quotes: ‘ ’ is a space. You can alsodefine a character literal with the Unicode value. A space could be defined likethis: ‘x20’. There are some special character (some nonprintable) literals that maybe useful, such as new line, horizontal tab, and so on. You express these charac-ters with special values, as shown in Figure 3.8.

38

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 27: APPLETS AND APPLICATIONS

SAMPLE PROGRAMS

I’ll start by giving you a very simpleexample. This is a Java application orwhat can be referred to as a stand-aloneprogram. (All three programs in thissection are stand-alone programs.) Theprogram in Figure 3.9 simply displays“Hey, Java is cool!”

public class sample1 {public static void main(String[] args) {System.out.println("Hey, Java is cool!");

}}

Figure 3.9: The syntax required for creating a Java “Hello World” program is quite simple.

The first statement of the program in Figure 3.9 names a class (sample1). EveryJava program must be inside a Java class. The Java compiler looks at the name ofthe class and not the name of the source file to determine the file name of thecompiled byte code. (This is similar to RPG II programs where you would definethe program name in the Header specification. The RPG compiler would alwaysuse the name in the Header specification for the compiled program name.)

Execution of a Java program always starts with the main function. If any parame-ters are passed to main, they are passed through a String array (in this case, the ar-ray is called args). In Figure 3.9, there is only one statement within the main

function System.out.println(“Hey, Java is cool!”). System.out is an object that refersto the system that is executing the program; println is a function or, in OO terms,a method of object System.out, which I am invoking. The println method printsthe STRING ARGUMENT (parameter) contained within the parentheses.

Figure 3.10 shows a slightly more complex sample program. The comments andcode in the example provide some insight into string handling.

39

SAMPLE PROGRAMS

Figure 3.8: Special characters can be insertedinto a Java string using special values.

Page 28: APPLETS AND APPLICATIONS

public class sample2 {public static void main(String[] args) {// The String class defines a stringString s = "Internet Expert";System.out.println("String variable s = " + s);// method length determines length of stringint n = s.length();System.out.println("Length of s = " + n);// method substring substrings variable ss = s.substring(0, 8);System.out.println("String variable s now = " + s);// change contents of string variable ss = s.substring(0,0) + "NewValue";System.out.println("String variable s now = " + s);

}}

Figure 3.10: The System.out.println method is an easy way to create simple screenoutput.

As shown in Figure 3.11, the Java program, using math, calculates a mortgagepayment. For simplicity, I’ve initialized the variable to the values I wanted touse. This way I didn’t have to get into I/O operations.

public class sample3 {public static void main(String[] args) {double principal = 202300.00;double yearlyinterest = 7.5 / 100;int years = 15;double monthlyinterest;double payment;monthlyinterest = yearlyinterest / 12;payment = principal * monthlyinterest

/ (1 - (Math.pow(1 / (1 + monthlyinterest), years * 12)));System.out.println("Your payment is ".+ payment);

}}

Figure 3.11: Mathematical operations are easily performed on Java’s basic data types (int,double, long, and float).

Notice the pow method of the Math class (Math.pow). Java doesn’t have anexponentiation operator, so you have to use a Math method.

40

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 29: APPLETS AND APPLICATIONS

EASY DOCUMENTATION WITH JAVA

As a C++ programmer, one of my earlier but unfounded criticisms of Java wasthat the class definitions were not separate from the code implementation. It is aC++ convention that your class definitions are kept in a “header” or *.H file andthe code is kept in a *.CPP file. The C++ headers are then very easy to review fordocumentation. But in Java, if you follow some simple commenting conventions,you can run the Java software development kit utility, Javadoc, over your Javacode to dynamically create HTML documentation.

■ Use description comment blocks delimited by a slash double asterisk (/**)and asterisk slash (*/) preceding every class statement, as well as attributeand method declarations.

■ For method declarations with parameters, add a line to the function’sblock comment with an @PARAM command for each parameter:

@param paramName parameter description

■ For method declarations with a return value, add a line to the function’sblock comment with an @RETURN command:

@return description of return value

Figure 3.12 shows a Java class that will self-document with Javadoc. Figure 3.13shows a sample HTML page that was generated from javadoc.exe over the pre-ceding class code.

There are some other @ commands that you may research on your own, such as@EXCEPTION, @VERSION, and @AUTHOR.

For complex classes, these HTML files are invaluable, and, with the simplicity ofcoding for Javadoc, there is no excuse not to use the @ command as a codingstandard. Javadoc can also parse some HTML tags, such as <PRE> and <TT>, aswell as some special prefixes such as x.

41

EASY DOCUMENTATION WITH JAVA

Page 30: APPLETS AND APPLICATIONS

/** EasyDocument class.* @version 1.0 07 July 1997* @author Don Denoncourt* This class does little more than exemplify self documentation* through simple coding conventions and javadoc.*/

public class EasyDocument {/*** variable1 is a primitive integer.*/private int variable1;/*** Does not do anything worthwhile but take parameters* that are properly documented.* @param x an integer parameter that is not really used.* @param y a character parameter that is also not used.*/public void doNothing(int x, char y) {;}

/*** Returns pi.* @return the value of pi.*/public float whatsTheValueOfPi(){ return 3.14;}

}

Figure 3.12: This code is a self-documenting Java class.

42

CHAPTER 3: AN AS/400 PROGRAMMER’S FIRST LOOK AT JAVA

Page 31: APPLETS AND APPLICATIONS

YOU’VE GOT TO TRY ITIf you’ve never programmed in C, C++, or Java, some of this material mightseem a little strange. But I encourage you to get yourself a Java development sys-tem (e.g., download Sun Microsystems’ JDK), look at the many chapters in thisbook, and start playing with the language. It really isn’t difficult, just different. Ithink before you know it, you’ll love it.

43

YOU’VE GOT TO TRY IT

Figure 3.13: The screen shows a sample HTML page generated with javadoc.exe.


Recommended