2 Introducing the Java Development Environment

This chapter will introduce Java and the Java virtual machine (JVM or Java VM), the environment in which your Java programs will run.

RUNTIME INTERPRETATION AND JAVA BYTE CODES

Java’s designers had a number of primary design objectives. As you have seen, object orientation is one of them. Another is the premise that a program can be compiled on any machine and the output of the compiler simply moved to another machine, where it will execute without changes. This concept is captured in the Java mantra, “Write once, run anywhere.”

In an Internet environment, the movement to the execution machine (an end user’s PC, for example) is automatically performed by the browser without any special commands by the user. The net result is simplified administration of the applications and immediate access to any Java application for the end user.

To accomplish this, the Java compiler does not create executable code—meaning a program that runs natively on a given system. Instead, the Java compiler creates an intermediate representation of your program. This representation is somewhere between source code and native machine code. It is called Java byte codes. These byte codes are the content that is moved to a computer system at runtime to be executed on that system.

Since the byte codes are not in a format that is native to any system, they can’t be executed directly on any system. Instead, a native program interprets the byte codes and performs the application functions expressed in the byte codes. This interpreter is called a Java virtual machine, because it creates a virtual system environment in which Java byte codes can execute.

This concept is not new. Interpreted languages such as LISP and SmallTalk have worked this way for years. Some cross-platform COBOL compilers (notably from MicroFocus and AcuCorp) also provide this same type of “instantaneous portability” feature, using a byte code or intermediate version of compiled COBOL programs. Also, Ruby on Rails, ASP.NET (where multiple languages can be used for the output of byte codes), PHP, PERL, Python, and so on provide some form of virtual machine environment. Figure 2.1 shows the compile and execution procedure for a simple Java application.

In theory, the only prerequisite for running a Java program on a system is that an appropriate Java virtual machine be available on that system. As you might suspect, the reality is somewhat different.

Operating system functions and some details of the way an application interacts with the operating system are not exactly the same across all operating systems. Java does a credible job of defining standards that shield most applications from these differences, but it does not cover all cases. As a result, some low-level application functions are not defined by Java, or they are left to the individual VM implementation to deliver.

A good example of these issues is the curious fact that Java doesn’t define a universal (or “pure Java”) notion of a standard output display device. The System.out.println statement in Figure 2.1 is not technically 100% pure Java, even though it appears in almost every Java reference manual! It is left up to the Java VM’s implementation of the System.out object to decide what to do with System.out.println.

Image

FIGURE 2.1
The Java compile and execution process.

To really complicate matters further, Java VMs are often executed as part of a browser application (such as Firefox or Microsoft’s Internet Explorer). Java applications that are embedded in an Internet document (called Java applets) execute as part of the browser interface. The browser actually controls some of the details of how the application looks (such as the default font to use).

Java applets, in particular, are most subject to portability problems due to the differences in browsers and the various versions of the Java VMs used by the browsers. The implication is that a software provider should test a product on several different combinations of operating systems/browsers/Java VMs, to make sure the application works correctly in all of the target execution environments. This has certainly been the case with many interactive Java applications. More importantly, Java applets are restricted to a very stern security model that limits their functionality.

Client-side Java applications running outside of the browser, on the other hand, are surprisingly portable. There are a number of class libraries available that define powerful mechanisms to build graphical user interfaces (GUIs). Sun provides the original Abstract Window Toolkit (AWT) libraries and the newer Java Foundation Classes (JFC)/Swing class graphical libraries, which run on all platforms. Any of these class libraries provide excellent mechanisms to build first-rate GUIs.

Another point to consider is that server-based Java applications are likely to be less susceptible to these variations, and most business logic is server-based. The majority of the differences between Java runtime environments arise from user interface issues. Since server applications don’t have their own user interface, they are, by and large, unaffected by most of the runtime environment differences. Server applications will experience some variations in runtime environments, but these variations are fairly technical in nature (such as the mechanism to use for access to the native system), and normally they are easy to isolate.

Enough with the concepts. It’s time to write some code. It’s a good idea to mix reading about concepts with working on those concepts.

In order to write programs in Java, you will need a few tools. At a minimum, you will need a Java compiler, a JVM to interpret and execute your code, and a text editor. The text editor can be one of your choice, from Notepad on Windows systems to vi in a UNIX environment. The only requirement is that it create vanilla text files without any special formatting characters (such as a word processor might put into a file).

If you are lucky (and smart), you will use an integrated development environment (IDE) from a Java tool vendor. IDEs combine compilers, JVMs, a nice editor, and some type of project management tool into an integrated system. Sun and BEA sell excellent graphical Java development environments. Eclipse, the open source IDE project started by IBM, is used by most Java developers (www.sdtimes.com/content/article.aspx?ArticleID=30020). I will discuss Eclipse in Chapter 17.

The IDE tools take full advantage of a graphical operating system, such as Windows, Linux, and Solaris. These products take most of the grunt work out of the development experience, and they allow you to focus more time on your programming problem and less on tedious chores like managing files.

Image

A popular nongraphical toolset is Sun’s Java Software Development Kit (SDK), which is part of its Java platform solution. The SDK includes a free Java compiler and runtime environment and is available from Sun at www.java.sun.com. It is also included on the CD-ROM. You can just download this to your PC and use it. Of course, it doesn’t have a graphical editor and is not a visually integrated development environment, but you can’t beat the price.

Sun also makes a robust graphical development environment for Java called Java Studio. Sun makes several versions of this tool and distributes the NetBeans edition of the product for free. Finally, the CD contains the Eclipse open source IDE.

Learning how to use a new development environment can be a difficult step in moving from COBOL to Java. These initial exercises are geared more toward helping you become familiar with a new environment than reviewing the concepts already discussed. After you’ve mastered (or at least come to terms with) the development environment, you’ll use these exercises to review the concepts presented. Therefore, you’ll begin by concentrating on learning the development environment instead of understanding the code samples. (The code samples are explained and reviewed later.) To help you get started, step-by-step introductions to the SDK for the Java 1.6 platform are presented.

Image

Commands that you are expected to execute (either with a mouse or by typing the command) are identified with the arrowhead marker at the beginning of the command.

GETTING STARTED WITH JAVAS SDK

Sun’s product has good introductory documentation available for it. An excellent one is on Sun’s Java Web site. The following steps will guide you through the process of creating your first Sun-flavored Java application and applet.

First, install the SDK development environment. You can download it from the CD-ROM included with this book or from Sun’s Web site. Follow the instructions on the installation Web page to install the software properly.

After it has been installed on your PC, the SDK utilities can be used from an MS-DOS command window. You can start up an MS-DOS window by using this menu path, beginning with the Windows task bar: Start > Run, then type in CMD.

In the command window, you can execute the Java compiler (javac.exe), the Java runtime (java.exe), and the applet viewer (appletviewer.exe). All these programs take parameters, such as the name of the Java file to be compiled. If you are using a Windows version before XP, you should also install the DosKey program (type doskey in the command window). This program remembers your DOS commands, which you can recall and edit using the cursor keys.

If the system cannot find the java.exe program after installation, you may need to add the directory that contains the SDK executables to your PATH environment variable. This variable controls how Windows finds programs to execute.

In Windows 98, you can use the sysedit function (menu path Start > Run > Sysedit) to edit the AUTOEXEC.BAT file. Assuming you have installed the SDK to the default directory (C:Program FilesJavajdk1.6.0_03), add a line to the end of the AUTOEXEC.BAT file that reads as follows: SET PATH=%PATH%; C:Progra~1Javajdk1.6.0_03in. Changing the AUTOEXEC.BAT file requires that you reboot your PC.

On Windows ME, XP, Vista, 2000, and 2003, use the System icon on the Control Panel to modify the environment variable directly. Add the SDK path (C:Program FilesJavajdk1.6.0_03in) to the end of this variable. The source can be modified with any text editor, including WordPad. Java source files are standard text files, including line-ending sequences (CR, LF on PCs). WordPad is very popular for this task because you can save and compile the Java source without closing down WordPad. Just make sure you save the WordPad files as text files, rather than as document files. Document files contain additional text formatting information that is not appropriate for Java. Freeware and shareware text editors are available on the Web.

Now, it’s time to get started.

  1. Make a directory to contain your Java files. From the DOS window, you can create a directory on the C: drive by typing the following:

    →   cd C:

    →   mkdir java4cobol

  2. Change the current directory in your command window to the directory you just created:

    →   cd c:java4cobol

  3. Using a text file editor, enter this Java source:

    public class HelloWorld {

         public static void main(String[] args) {
              System.out.println ("Hello World!");

         }
    }

  4. Save the source to a file named C:Java4cobolHelloWorld.java.

  5. Compile your Java source with the SDK compiler (java.exe) in the DOS command window:

    →   javac HelloWorld.java

  6. Your HelloWorld Java program should compile successfully. If it doesn’t, there are three (or more) possible problems:

    • Cannot find the javac program: Check your PATH environment variable by using the set command in the DOS window. It should contain the directory where the program javac.exe is (on Windows, normally C:Program FilesJavajdk1.6.0_03in).

    • Cannot find HelloWorld.java: Check the spelling, and make sure you used the correct case. Are you in the directory where the source file was saved (C:java4cobol)?

    • The compile reported some errors: Check your source file. It should be exactly as presented here.

    • Check the Sun Web site for additional suggestions.

  7. Now run your program, using the Java runtime that comes with the SDK:

    →   java HelloWorld

  8. If you’ve done everything correctly, your MS-DOS window should look like Figure 2.2.

Image

FIGURE 2.2
The Hello World! program.

Congratulations! You should be proud of your first Java program. It is full of potential.

Experiment with the program a little bit in this environment. You can make the changes in the text editor you have chosen. Compile it by typing javac Hello-World.java in the command window. After your program is compiled, you can execute it from the MS-DOS command window by typing java HelloWorld.

  • Change the message from “Hello World!” to “Watson come here!”

  • What happens if you add a second System.out.println statement to your program?

APPLETS WITH SDK

Now you’ll write your first Java applet in this environment and run it in the Applet viewer.

  1. Using either Windows Explorer or a DOS command, create a new directory (or folder, in Explorer terminology) called “applet” in the java4cobol directory. Your applet files will be stored in this directory.

  2. Using a text editor, create a Java source file named HelloWorld.java in this directory. The source file should contain these statements:

    import java.applet.Applet;
    import java.awt.Graphics;
    public class HelloWorld extends Applet {
         public void paint(Graphics g)
         {
              g.drawString("Hello Applet World!", 5, 25);
         }

    }

  3. In the DOS command window, change the current directory to your applet directory:

    →   cd c:java4cobolapplet

  4. Compile your applet using the javac compiler:

    →   javac HelloWorld.java

    Again, your applet should compile successfully at this point. If it doesn’t, review the previous suggestions.

    Applets are meant to be executed in a hosting environment, often a Web browser. Web browsers display information in HTML documents and are instructed to execute applets by special commands in the HTML document. The HTML command to execute an applet is the <applet> tag. This tag instructs the browser to run the applet specified in the applet tag.

    You do not need to be an HTML expert for this step, but you will need to create a simple HTML document.

  5. Using a text editor, create an HTML document named HelloWorld.html in your applet directory. The file should contain these statements:

    <html>
      <head>
        <title>HelloWorld</title>
      </head>
      <body>
        <hr>
          <applet
             code=HelloWorld
             width=200
             height=200>

          </applet>
        <hr>
      </body>
    </html>

    Remember to save this file under the name HelloWorld.html, and to save it as a text file, not as a document.

  6. In the DOS command window, execute the APPLETVIEWER program to display your applet. Make sure you are in the applet directory.

    →   appletviewer HelloWorld.html

    If you’ve done everything correctly, your MS-DOS window and your applet viewer window should look like Figure 2.3.

Image

FIGURE 2.3
“Hello World!” in the applet viewer.

Experiment with this applet as well. You can make the changes in the text editor, then recompile and execute the program in the DOS command window. You will need to exit the applet viewer every time you run your program by clicking the X widget at the top right of the applet viewer window. Or, you can use the Reload function in the applet menu.

  • Change the message from “Hello World!” to “Watson come here!”

  • What happens if you add a second g.drawString statement to your program?

  • Why do you think only one message showed up? (Hint: drawString is a graphically oriented function, whereas println is a line-oriented function.)

  • What do you think the numbers 5, 25 control on the page?

  • What happens if you change the 5 to a 6?

  • What happens if you change the 25 to a 35?

Now that you’ve had some success with your first Java program, let’s take a minute to discuss some of the rules of the road that a Java program must observe.

CLASSES AND FILENAMES

Java source filenames and public Java class names must all have the same name. The compiler automatically creates a class file with the same name as the source file. Consider the first example class, HelloWorld (refer to Figure 2.1).

The name of this class (HelloWorld), its source filename (HelloWorld.java), and its output file (HelloWorld.class) all have the same name. Because of this, the runtime system can easily find the class file for HelloWorld when it is first needed by looking for a file named HelloWorld.class. Notice that the Java compiler needs the .java extension, but the runtime system assumes the .class extension.

CLASSPATH

But where does the runtime system look for the HelloWorld.class?

In most cases, this is controlled with the CLASSPATH setting. The CLASSPATH setting details a list of directories (or class archives, which can be jar or zip files) on the host operating system that contain classes. The Java runtime searches these directories (in the order they are listed) for your class files as they are required. This is similar to the way the PATH variable is used in Windows to find executable program files. The CLASSPATH variable can be set either as an environment variable (that is, a variable defined to the operating system) or as an optional argument to the runtime instance. The optional argument at runtime is the preferred approach because it doesn’t mess up other programs’ class paths.

For example, the standalone SDK runtime interpreter searches the c:java4cobol directory for your classes, given this runtime option:

→   java -cp c:java4cobol HelloWorld

The -cp command argument tells the runtime to search in the c:java4cobol directory for classes. The CLASSPATH argument can be a list of directories as well.

→   java -cp c:windowsjava;c:java4cobol HelloWorld

The CLASSPATH can also include zip or jar files (archive files built by the jar utility) that contain packages bundled by zip or jar utilities. I will say more about this later.

Image

Normally, you will not need to include the standard runtime classes; Java provides a mechanism to find these automatically.

The system environment variable CLASSPATH works in much the same fashion as the CLASSPATH command line argument. It can contain a list of directories in which the runtime system can search for classes. Its use is discouraged, however, since this variable applies to all Java runtimes on the system. As a result, coordinating the search requirements of multiple Java applications (especially if they are from various vendors) can be difficult.

Most development environments provide a way to assign a CLASSPATH variable to a project. You will need to consult the documentation for the development environment you are using to learn how to do this.

CODEBASE

Instead of the CLASSPATH setting, applets use the CODEBASE reference. This parameter specifies the directory that contains the initial applet, along with any supporting classes it requires. This is the syntax:

<applet
CODEBASE = codebaseURL
code=HelloWorld
width=200
height=200>
</applet>

As you might suspect, CODEBASEs are defined in terms of a uniform resource locator (URL) on the Web server. For security reasons, Java applet CODEBASE references must be on the same Web server (that is, must have the same domain name) as the HTML page that started the applet.

PACKAGES

A package is a way for the Java developer to group classes that are in some way related. For example, a GeneralLedger package would likely contain an Account class and a Ledger class. These classes might implement the business logic necessary to manage account information or to record a transaction in the Ledger.

These classes can define package variables and methods that would be available only to other classes in this package. In addition, public members are automatically made available to classes in the same package. Consequently, classes in a package do not need to import other classes in the same package.

Java defines a default package for classes that do not belong to an explicit package. You’ve already used the default package in your exercises. Until now, its primary benefit has been that it is a convenient mechanism to access the various example classes. But you could use a Java package to organize the examples.

To do this, you might define a java4cobol package. Simply include the package statement as the first uncommented line in your Java source file:

package java4cobol;

     public class ErrorMsg     {

          public String msgText;
          public int    msgSize;
               ...
       // Some logic
               ...
    }

Now the ErrorMsg class is part of the java4cobol package. The fully qualified name (FQN) of this class now becomes java4cobol.ErrorMsg.

Packages can have many parts to their names. For example, you could define a java4cobol.message package, and place all of your message-related classes into this package:

package java4cobol.message;

     public class ErrorMsg     {

          public String msgText;
          public int    msgSize;
               ...
       // Some logic
               ...
    }

In this case, the complete name of your ErrorMsg class would be java4cobol.message.ErrorMsg. Notice that java4cobol and java4cobol.message are different packages. Also, package names should be all lowercase to ensure they will work properly on all operating systems.

INSIDE A PACKAGE

Since all the classes in a package are related, it follows that they can take advantage of each other. For one, the default access control definition for classes, methods, and variables is package. This means that any one of these items that does not have an explicit access control qualifier is visible to all classes in the package.

Another advantage is simpler naming of class names in your code. If a class is part of a package, other classes in the package can refer to it using only its short name instead of its fully qualified name. For example, any class in the java4cobol.message package can refer to ErrorMsg as simply ErrorMsg instead of the more precise java4cobol.message.ErrorMsg.

A class from one package can still refer to classes in another package by using the fully qualified name. To continue the example, an Account class in the general_ledger package could refer to the ErrorMsg class by its package.class-name: java4cobol.message.ErrorMsg.

package general_ledger;

     public class Accounts      {

          public String accountID;
          public BigDecimal    accountBalance;
               ...
// Create a new ErrorMsg object. Use the complete package name and class
// name.
           java4cobol.message.ErrorMsg accountNotFound =
                      new java4cobol.message.ErrorMsg ();
           ...
     }

However, this is more typing than the average programmer is willing to do. So, Java has defined a way for you to announce which classes your class will use, called the import statement, which must follow any package statements in your program. It tells the compiler that your class might refer to the classes identified in the import statement. The full class name is described only once in the import statement; afterward, the compiler knows to use the full name whenever it sees the short name.

package general_ledger;
import java4cobol.message.ErrorMsg;

     public class Accounts  {

          public String accountID;
          public BigDecimal    accountBalance;
               ...
// Create a new ErrorMsg object. No need to use the full class name or FQN.
          ErrorMsg accountNotFound = new ErrorMsg ();
               ...
     }

This type of import statement is officially named a single-type-import declaration statement.

For brevity’s sake, a class can identify all of the classes in a package by using the asterisk (*) wild card instead of listing each class name. This statement instructs the compiler to import all the classes in java4cobol.message as they are needed, including ErrorMsg:

package general_ledger;
import java4cobol.message.*;

This type of import statement is officially named a type-import-on-demand declaration statement.

Although the import statement behaves in a manner similar to the COBOL COPY statement, it is really quite different. No code is actually imported, just the public class definitions. Significantly, the import statement tells the compiler to import the class file (the compiler output) and not the Java file (the source file). It is more of an aid to the compiler than it is a technique to copy code from another class.

Now that the Accounts class contains this import statement, it can refer to any class in the java4cobol.message package using only the class name. You do not need to use the full package.classname syntax.

NAME COLLISIONS

When using the wild card import statement, it is possible for a class to have the same name in two separate packages, or for your program to create a name that collides with a name in an imported package. In this case, the package name can be used to uniquely identify a class in a package:

package general_ledger;
import java4cobol.messages.*;

     public class Accounts {
// Create a String object with the same name as the class ErrorMsg.
         String ErrorMsg;

         public String accountID;
         public BigDecimal    accountBalance;
               ...
// Create a new ErrorMsg object. Specify the full package name.
         java4cobol.messages.ErrorMsg accountNotFound =
               new java4cobol.messages.ErrorMsg ();
               ...
// Copy the msgText from the ErrorMsg class to the local ErrorMsg String
// variable.
         ErrorMsg = java4cobol.messages.ErrorMsg.getErrorMsg();
     }

PACKAGES AND FILENAMES

Java packages and the directories on your computer’s file system are closely related. As a rule, any package name must have a corresponding directory name on the host operating system, and it is case sensitive. This applies to both the development environment and the runtime (deployment) environment.

The name of a package maps to its filename location. In this example, you would expect to find a directory named ..java4cobolmessages and ..general_ledger (on UNIX systems, the slashes go the other way: .. /java4cobol/messages and .. /general_ledger). Notice that the introductory periods (..) in the package names (java4cobol.message) are replaced with the correct directory separator character (java4cobolmessage or java4cobol/message).

The package name does not normally start at the root directory of the host file system. Instead, Java uses the CLASSPATH variable to point to a list of initial directory names, which are then searched for specific package directory names as well as class names.

In the example, if you set CLASSPATH to c:windowsjava; c:, the compiler will look in both the C:windowsjava directory and the root directory of the C: drive for a directory named java4cobolmessages. In this directory, it will look for a file named ErrorMsg.class.

It is likely that you will use packages from other vendors, or perhaps you will create packages that some other development or deployment environment will use. Since it is not realistic to coordinate class names or package names in advance, a convention is often used to group packages based on the origin of the package. Many package names are prefixed with the Internet address (domain name) of the provider, but in reverse order. Sometimes the .com portion of the domain name is left out.

For example, if an organization’s domain name is mycompany.com, the java4cobol.message packages delivered by this company will likely be in a directory named com.mycompany.java4cobol.message, or mycompany.java4cobol.message.

Your source files should use the same conventions, but with a different initial directory so that source files and class files are kept separate. In this way, you can ship your class files and not your source files. As applied to the example, the class files would be in classesmycompanyjava4cobolmessages, and the source files (with the .java extension) in sourcemycompanyjava4cobolmessages.

COMPRESSED PACKAGES

Finally, the Java compiler and the Java runtime system can read compressed (or zipped) files that might contain many classes. Think of these compressed files as the contents of a directory (including perhaps several subdirectories) packaged into a single file. Microsoft’s standard for packaging compressed classes is their cab technology; other vendors use the jar file technology for this purpose. This discussion focuses on the jar file convention, although many of the benefits and techniques would apply equally to cab files.

You can add a jar file to your CLASSPATH like this:

java -cp c:java4cobol.jar HelloWorld

In this, the Java runtime program would look in the jar file to find the class HelloWorld. Jar files provide several benefits, including these:

  • Related classes can be organized and managed in a single archive. This simplifies the administration of the classes.

  • A single request (for the jar file) can copy many classes from one system to another. This is especially important in an Internet browser, where a single HTTP request for the jar file will replace several individual HTTP requests (one for each class in the package). The browser issues HTTP requests to copy files from the Web server to the browser. Combining several requests into a single request is a significant performance benefit.

  • The classes in the jar file are compressed (using the zip compression format). This can improve download performance and reduces disk space requirements.

  • Individual classes can be digitally signed by their author and checked at runtime for authenticity. Only the single file needs to be checked, instead of each component in the file.

APPLICATIONS VS. APPLETS

Java programs run in one of three contexts: as an applet, as an application, or as servlets. I discuss server-side Java programs in more detail toward the end of this book in Part III, “Introducing Enterprise Java.”

As the name suggests, an applet is an application fragment. It is not a complete application but rather an extension of another application. Most often, the application extended is a browser, such as Firefox or Microsoft’s Internet Explorer. In fact, any application can be extended with Java applets. The only requirement is that the application to be extended must provide a Java runtime environment.

Conversely, a Java application is a complete application. It can run as a stand-alone application and independent of any other application. A Java application still needs a runtime interpreter, but this interpreter is a standalone program whose only responsibility is to execute and support Java applications.

A standalone interpreter is often a native program, suitable for executing on the host platform. For example, Sun’s standalone interpreter is named java.exe in Windows, and java in every other environment, and it is executed like any other application. Sun provides a version of the Java program for Windows, Linux, and the Solaris operating systems. The only job of the standalone interpreter is to execute the Java byte codes and to perform the functions requested by the application.

REVIEWING THE SAMPLES

I kind of rushed through some of the code and the changes made to it in an effort to explain the development environment issues, so let’s take a minute to review, starting with the first application.

  • Your first program was a standalone application. That is, it only needed a runtime interpreter to execute, which was java.exe.

  • The main program (the class that gets the ball rolling) in a Java application must have a specific interface. It must have a public method with this method definition:

    public static void main(String[] args)

  • This method accepts a single parameter (named args in the example). This parameter must be defined as an array of Strings (String[]). The String array represents the runtime arguments to the program (as in jview HelloWorld argument1 argument2).

  • The class that contains this method (HelloWorld, in the example), does not need to be any particular name, but it may need to be public, depending on the requirements of the runtime environment. It also must be a static class, meaning only one instance of the class can exist at a time.

  • The internal name of the class (in the source program HelloWorld.java) and the external name of the class (the HelloWorld.class file built by the compiler) must be the same.

  • A Java application run in this manner does not expect to have a GUI environment available to it, but it can. It does expect to be able to write to a logical file, known as standard out, and to read from standard in. These files are more or less the equivalent of the ACCEPT and DISPLAY verbs that interact with the CRT in COBOL programs.

  • For most Windows-based Java interpreters, standard out and standard in are directed toward an MS-DOS command window. Java applications run this way are not graphical applications.

  • The statement System.out.println ("Hello World!"); writes to the console, or standard out. It performs the println() method in a built-in object named System.out. This method accepts a String input parameter and writes it to standard out. Think of it as analogous to this COBOL statement:

    DISPLAY "Hello World!".

  • Subsequent calls to println write a new line of text to standard out.

    The next program you wrote was a Java applet.

  • An applet expects to be supported by some type of graphical hosting environment. Most often, the graphical hosting environment is a browser.

  • Some standalone Java runtime environments also provide a built-in graphical hosting environment, or applet viewer. For the SDK, this was APPLETVIEWER.EXE. The applet viewer is an excellent tool for testing your applets.

  • The main program (the program that gets the ball rolling) with a Java applet is the hosting environment (the browser or the applet viewer). It calls the paint() function in your class so that you can display information to the screen. The paint() function must have a specific interface. It must have a public method with this method definition:

    public void paint(Graphics g)

  • This method accepts a single parameter. It is a Graphics object (named g in the example).

  • The class that contains this method (HelloWorld, in this example) does not need to be any particular name, but it does need to be public. This class must be of the sort that extends, or inherits, from a class named Applet.

  • The statement import java.applet.Applet; at the beginning of the class tells the Java compiler where to find the Applet class.

  • The internal name of the class (in the source program) and the external name of the class (the HelloWorld.class file built by the compiler) must be the same.

  • A Java program run in this manner expects to have a GUI environment available to it. It also expects to be able to write to a logical file known as standard out and to read from standard in.

  • Standard out and standard in are not well defined for these types of programs.

  • The statement g.drawString("Hello World!", 5, 25); writes to the graphical environment. It performs the drawString method in the Graphics class. This method accepts a String input parameter and writes it to the graphical environment. There are additional controls to this method. In the example, I’ve specified the starting position in the graphical window to place the String. Think of it as analogous to this type of COBOL statement, extended with the ability to position the text anywhere on the screen:

    DISPLAY "Hello World!" AT COLUMN 5 LINE 25

  • The statement import java.awt.Graphics; at the beginning of the class tells the Java compiler where to find the Graphics class.

  • Subsequent calls to drawString write text to the specified place in the graphical window.

    g.drawString("Hello Applet World!", 5, 25);
    g.drawString("Hello Applet World!", 5, 25);
    g.drawString("Hello Applet World!", 5, 25);
    g.drawString("Hello Applet World!", 6, 25);
    g.drawString("Hello Applet World!", 5, 25);
    g.drawString("Hello Applet World!", 5, 35);

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset