Applications, applets, and hybrids

Java 101 charts a new course, and explores applications, applets, and hybrids

If you've been following Java 101, you know that Jacob Weintraub has created an excellent series of articles designed to help Java newbies become Java developers. However, as Jacob can no longer continue this column, JavaWorld has passed the torch to me.

You'll quickly discover that my route to becoming a Java developer follows a different path. For example, I prefer to talk about the programming aspects of Java that are not object-oriented (such as types, variables, operators, expressions, and statements) before delving into its object-oriented side. I believe that approach will enhance Java 101's natural flow from one topic to another -- a flow that seamlessly moves from start to finish. To facilitate the discussion, occasionally I will present an advanced concept before I fully explain it. As a result, you'll encounter brief explanations about more advanced topics as you work your way through this and future articles.

Java 101 will introduce many example programs. Each program is compiled with Sun's Java 2 Platform, Standard Edition version 1.4 (also known as SDK 1.4) compiler and tested on the Windows 98 SE platform. Although I'll try to keep Windows references to a minimum, that won't always be possible, so I'll warn you when an article strays into the world of Windows.

Because I haven't spent much time dealing with Java from the server perspective, this column will focus on client-side Java. That doesn't mean we won't explore topics such as Remote Method Invocation and JDBC, that bridge the client and server sides. However, I will not present servlets, Enterprise JavaBeans, Java Server Pages, and other server-side topics. To get a better idea of the subjects I will cover, see the sidebar, The Road Ahead, for the Java 101 course outline.

In this month's article, I discuss the structure of application, applet, and hybrid programs. From an application perspective, you might find some overlap from Jacob's earlier articles, but I will also introduce quite a bit of new content.

Program categories

Java gives you the ability to create four kinds of programs: applications, applets, hybrids, and servlets. I discuss the first three programs in this article. To learn more about servlets, please consult the Java 2 Platform, Enterprise Edition documentation.

Applications

An application is a standalone program consisting of at least one class with a main() method. That method features the following signature:

public static void main (String [] args)

The public keyword means main() is callable from outside the class in which it's declared. The static keyword means main() is callable without an object reference. In other words, the JVM does not need to create an object from the class that declares main() before calling main(). Finally, the void keyword means main() doesn't return a value.

As with other methods, main() has a parameter list, a list of types and variable names. In main()'s case, only one parameter appears -- args. That parameter is declared a reference to -- also known as address of -- an array of String objects. Each object contains the contents of an argument passed to the application by way of the program's command line. Note: You do not have to use args as that parameter's name. You can just as easily specify chickens, as in String [] chickens.

Listing 1 presents source code for an application called App. That application prints out a list of arguments that are passed to itself by way of the command line.

Listing 1. App.java

// App.java
class App 
{
   public static void main (String [] args)
   {
      System.out.println ("Command arguments\n");
      for (int i = 0; i < args.length; i++)
           System.out.println (args [i]);
   }
}

TEXTBOX:

TEXTBOX_HEAD: Comments

Listing 1 illustrates a technique that I use to identify programs -- at the top of a source file, I place a comment that identifies the source file's name. I find that comment useful in keeping track of programs. If you're not familiar with the concept of a comment, it's nothing more than source code documentation that only has meaning at the source level. When source code is compiled, the comment is thrown away. We'll look at comments again next month.

:END_TEXTBOX

Code within App's main() method calls one of the out object reference variable's println() methods to output information to the standard output device. Typically, that device is a command window such as the Microsoft Windows DOS window, although the device can be redirected to a file. (I will demonstrate that redirection in a subsequent article.) The period character separates the println() method call from the out object reference variable. In turn, out is declared in a class called System and separated from System by a period character. An object reference variable closely resembles a C or C++ pointer: It's a variable that contains the address of another variable. You'll receive quite a bit of exposure to object reference variables in upcoming articles.

If you've worked with C or C++, you're probably familiar with the structure of the for loop statement (that appears in source code via keyword for). The for loop statement repetitively executes one or more statements for either a specified number of times or indefinitely. (In future articles, I will explore the for loop statement and other statements in detail.) In App's case, for executes a System.out.println method call for each argument that was passed to that program on the command line. Notice args.length. In Java, length is a property of an array, and it returns a count of array elements.

At the command line, type javac App.java to compile App. If you've entered everything as shown, you should end up with a class file called App.class that contains App's byte code instructions. So how do you run App? Take a look at Figure 1. That figure shows App running from the command line with three arguments: one, two, and three.

Note: Figure 1 shows App running under Windows 98 SE. Unix and Linux run App similarly. However, when run under the Mac, you'll probably have to complete a little more work. I'd love to show you how to do that, but I've never used Java on a Mac.

Figure 1. Running App with three arguments

The java program executes an application. Under Windows, that program is stored in an executable file called java.exe. As with javac, java is specified at the command line. The name of the class file that contains the main() method then follows java.

The java program looks for the main() method in the class file. If it doesn't find main(), it outputs an error message. (As you can see from Figure 1, you DON'T specify the .class file extension.)

Arguments can follow the class name, but they are optional. In Figure 1, those arguments are one, two, and three. java creates a String array (by way of the Java Native Interface -- JNI), and populates each element with a reference to a String object containing the characters composing an argument. Once complete, the main() method is called (by way of the JNI) and passed a reference to the String array.

Suppose you were to type java App * at the command line. What do you think the command window would display? If you think the answer is an asterisk, check out Figure 2.

Figure 2. Using a wildcard character to specify an argument

Figure 2 shows App displaying the names of files located in the same directory as App.class. It turns out that the asterisk character represents a wildcard. In other words, it represents all filenames in the current directory. When java builds the String array, it obtains a list of all the current directory's filenames, and places each filename in a separate String object, which is then stored as an element in the array.

Try running java App * *. Guess what will display. Because each asterisk causes java to obtain a list of all file names, you'll see two copies of all file names in the current directory.

Suppose you write a Calculator application that multiplies two numbers with the asterisk, as in java Calculator 4 * 3. Based on the previous discussion, 4 and 3 will not multiply. If you want the asterisk to be interpreted as itself -- and not a wildcard -- you must surround it with a pair of double quote characters. For example, you would type java Calculator 4 "*" 3. Furthermore, if your argument contains embedded space characters, and you want to include those space characters as part of the argument, you must use double quotes. For example, type java App "my compound argument" at the command line to specify my compound argument as App's single argument.

Our first Java application consisted of a single class. However, you can also create applications that consist of multiple classes. Furthermore, each class can have its own main() method. To see what that situation looks like, check out Listing 2.

Listing 2. Fred.java

// Fred.java
class A
{
   public static void main (String [] dogs)
   {
      System.out.println ("Class A main() method");
   }
}
class B
{
   public static void main (String [] chickens)
   {
      System.out.println ("Class B main() method");
      System.out.println ("Num args: " + chickens.length);
   }
}

Listing 2 presents source code stored in a file called Fred.java. That source code consists of two classes: A and B. When compiled (as in javac Fred.java), you end up with two class files: A.class and B.class. If you were to type java A, you would see Class A main() method in the command window. However, if you were to type java B, the command window would display Class B main() method, followed by a line that begins with Num args: and identifies the number of arguments passed on the command line.

Is Fred one application or two applications? The answer depends on your perspective. Normally, an application consists of a single class with a main() method. As you've seen, you run the application by specifying java and the name of the class that contains main(). However, you might find yourself placing a main() method in other classes (for debugging purposes). To prevent confusion for anyone using your program, either remove all main() methods except the main() method that starts the application, or identify the class file containing the official main() method before deploying the application.

In addition to java, the Java 2 SDK includes a javaw program that you can use to run applications. That program is almost identical to java, except that javaw does not display a command window when running an application (unless you run the application through a Windows batch file, which automatically opens a command window). For example, suppose your class file called GUIDemo is stored in the c:\jdk1.4\projects directory (assuming Windows). You decide to create a Windows shortcut for running that program, and choose the following command line: java -cp c:\jdk1.4\projects GUIDemo. (The -cp option tells java where to find a class file called GUIDemo.class.) When you select the shortcut, a command window pops up along with GUIDemo's GUI window. However, if you change java to javaw, you won't see the command window.

Now that you've had a chance to play with applications, let's take a look at the second category of Java programs -- applets.

Applets

An applet is an application that runs in the context of a Web browser that controls the applet. Because a rectangular area of the Webpage displays an applet's output, applets are described as being embedded in Webpages. Furthermore, by calling certain methods -- which we'll shortly investigate -- the browser manages an applet's life cycle.

An applet's class files download automatically to a user's machine when the user surfs to a Webpage containing the applet. Once downloaded, the browser's virtual machine or the Java Plug-in software executes those class files. (See Resources for an article that explores Java Plug-in.)

Imagine a malicious person creating an applet that deletes files, wastes reams of printer paper, steals passwords or other sensitive information, and so on. An applet with unrestricted access to a user's machine could perform all of those misdeeds. For that reason, applets can only execute limited functions. For example, an applet cannot perform any file-related activities.

Sun has established a specific (and involved) procedure for turning restricted applets into unrestricted applets. However, unrestricted applets can only run under the user's permission. (We will explore that subject in a future article.) To be an applet, one -- and only one -- of the applet's classes must conform to the following pattern:

public class class_name extends java.applet.Applet
{
}

The required public keyword gives the Web browser access to the applet. The extends keyword indicates the object-oriented programming concept of inheritance and suggests that the class_name class inherits applet capabilities from a class called Applet (located in the java.applet package -- an organizational mechanism for classes and class files -- to be explored in a future article).

Each applet has a life cycle. An applet is initialized (once and only once), started and stopped (one or more times during its life), and destroyed (once and only once). The browser calls one of four methods at significant points during that life cycle to indicate that the applet has entered another phase of existence. Those methods are init(), start(), stop(), and destroy().

1 2 3 Page 1