Chapter 8

Developing Java Applications


CONTENTS


The last chapter introduced you to Java applets. This chapter is devoted to a term most programmers should already be familiar with: the application. Applications are the more traditional type of programs that are used in less recent programming languages like C and Pascal. You learned in the last chapter that applets are a new strain of Java programs designed with an Internet readiness built into them. In this chapter, you will learn about Java applications and how they differ from Java applets.

In general, most Java enthusiasts have seen a Java applet on the Net in one place or another. If you are not in this category, then point your Java-capable browser to the following site for an example of a Java applet animation: http://cafe.symantec.com. The two coffee mugs are animated based on the animation applet that comes with the Java Developer's Kit (see Figure 8.1).

Figure 8.1 : An example of animation on the Net (the coffee cups are animated with Java).

Probably one of the most powerful (but as yet untapped features) of the Java programming language is that applets are only half of the entire Java language picture. Applets are the celebrated way of creating Java programs, leaving regular Java applications in the minority. There are probably only a few Java enthusiasts who have hands-on experience using Java applications. This is the result of the extreme exposure of the Internet and not of deficiencies in the applications themselves. The Internet is not a place from which applications are designed to be accessed. Nevertheless, Java applications are no less powerful-and in some situations much more versatile-than their applet counterparts. Java applications are just like applets in that they are multiplatformed and bytecode-verified. However, as you learn in this chapter, because Java applications are designed to exist inside a secure environment, they are not as restricted as applets typically are.

Java applications can be used as client/server solutions or in an Intranet environment-pretty much in any already secure environment. Anatomically, Java applications are based on a more traditional program design model, very similar to that of C/C++.

Note
An intranet is a smaller, self-contained Internet that is mostly employed by corporations as a way of connecting people to information. The advantage of intranets for Java applications is that they have an already secure internal environment from which Java applications can be used without having to impose all sorts of restrictions on your application.

Topics covered in this chapter include the following:

The next section covers the similarities and differences between applets and applications.

Applications versus Applets

In essence, applets and Java applications share many of the same resources and features. As you will learn in the next section, the major anatomical difference between an applet and an application that makes both of them unique is that an applet extends the java.applet.Applet class, and an application utilizes the main() method. On a higher level, an application is not as restricted as an applet in terms of what it can access. On the other hand, applications cannot be embedded into HTML pages for any Internet user to view with a Java-capable browser. Applets and applications overlap in many areas, but they are specifically designed for different environments. Figure 8.2 shows a visual interpretation of the differences and similarities between applications and applets. Basically, in many core respects they are the same, but they are unique in the audiences they are trying to reach.

Figure 8.2 : Venn diagram of java applications and applets.

Review of Java Applets

In the preceding chapter, you were introduced to the java.applet.Applet class. In order to tell Java that this program is going to be an applet, all that you basically need to do is create a subclass of the Applet class. Everything that makes up an applet is inherited from the superclass java.applet.Applet. Included in this inheritance are the basic user interface, methods for accessing parameters from an HTML page, and several methods known as life-cycle methods that are called directly by the system you use to organize your program. Another method that is part of the java.awt.Component class (which would be a super-super-super class to the class containing your applet) is the method paint(), which is used to draw various things in your applet's pane. The following shows an example of what the structure of a typical applet might look like:

import java.awt.Graphics;
class ABClass extends java.applet.Applet {
    public void init() {
        /* Initialize any variables, images, etc here.
        Any initialization that only needs to be done once should be
        included here because this method is called only once. */
    }
    public void start() {
        /* This method can also be used for initialization.
        However, the difference for this one is that it is used for
        components in your applet that need to be initialized more
        than once, or if the reader leaves the applet and then
         returns. This method can be called more than once. */
    }

    public void stop() {
       /* This life cycle method is the counterpart to start().
       Any code to suspend execution should be retained here. */
    }

    public void destroy() {
        /* This method is used to clean up the applet before it is
       finished. This method is called only once. */
    }
    public void paint(Graphics g) {
        /* Any code to draw, write, or color things on the
        applet pane belongs here */
    }
}

In the preceding pseudo-applet, each method is called by the system at a particular moment, under specific circumstances, or in a special order. Some of the methods can be called more than once depending on how the user engages the applet and the environment in which the applet is being run.

To review more closely the logistics of an applet, the fact that an applet is designed to run in the heterogeneous and possibly unsecured environment of the Internet has imposed several restrictions on it. Most of this is review from the last chapter, so this explanation highlights an applet in its strictest sense, pointing out potential differences with that of applications. Also, note that in certain situations, there are exceptions to the following restriction, even in applets. In some cases, these restrictions can be lowered depending on the type of Internet browser running the applet and its configuration.

Applets cannot read or write to the user's file system. This means that the applet cannot access anything locally or place anything locally either. For example, many Windows-based applications written in C utilize an initialization file (an .INI file) in 16-bit Windows or the Registry in 32-bit Windows to store information about the application and any user preferences. This is not possible in the current applet model and imposes a challenge to traditional programming techniques. This limited access can also include just checking to see if a file even exists on the user's system.

Applets cannot utilize native methods, load shared libraries, or run any programs that may be on the user's system. The major security concern here is that native methods and local shared libraries (such as DLLs) can facilitate a loophole in the Java security model described in the previous paragraph.

Applets cannot communicate with any server other than the one from which they originated. In some cases, an encrypted key can be used to verify a particular applet to a server, or a server accessed due to a configuration with the Internet browser, but access to any server on the Net cannot be assumed.

Overall, applets provide a different format for program execution and a very tight security model, which is necessary in the very open environment of the Internet.

Introduction to Java Applications

Java applications are different from Java applets in several ways. On the inside (that is, the source code level), you do not need to extend any class in the Java class library when creating an application. As a result, you do not have a set of basic methods that you override to execute your program. Instead, you create a set of classes that contain various parts of your program, and then you attach a main() method that will contain the code used to execute your code. The main() method is very similar to that of the C/C++ model; it is here that Java will start the actual execution of your application. The following shows what the structure for a typical Java application would look like this:

public class TheClass {
    /* variables and methods specific to the class TheClass
    are located here. */
    class ABClass {
        /* The body of the class ABClass
        is located here */
    }

    public static void main(String argv[]) {
    /* The actual execution of the application
    is located here. **/
    }
}

Note
The modifiers before the main() method-public, static, and void-must be present every time you use the main() method. public lets it have maximum exposure inside the current class. static causes this method to no longer need instancing in order to be available to all of the other methods in the current class. void means that there is no returning value coming from this method.

The main() method shown in the preceding code is the system method that is used to invoke the application. As mentioned earlier, any action code should be located in main(). The main() method is more than just another method in a Java application. If you do not include a main() method in your application when you attempt to run it, you will receive a message similar to the following error message:

In the class TheClass: void main(String argv[]) is undefined

Looking at a higher level in Java application topology, the major point to note is that in a typical Java application security model, an application can use native methods and access the user's file system. If the application and the user's environment are configured properly, it can also access all kinds of stuff from the Net. Of course, the price for all of this built-in versatility is that an application cannot be embedded in an HTML page and downloaded from a Java-capable browser.

In most cases, a Java application should look very similar to a typical C/C++ application. In this chapter, you are going to create several applications to exemplify some of the features and methods specific to a Java application. All of these will be based solely on console-based Java applications, because at this point you will not cover the AWT (Abstract Window Toolkit) until Part II, "Using the Java Packages," in this book. So remember that all Java applications can be used to create Windows-based applications complete with dialog boxes and an event handler.

Java Applications: An Example

Start by creating an application that you can execute at the command prompt. Using the Java Developer's Kit and a text editor, start by creating a new file called First.java and enter the code from Listing 8.1 into it.


Listing 8.1. The code for First.java.
 1:public class First {
 2:
 3:    //variables for class First
 4:    String name;
 5:    int accountNumber;
 6:    float balance;
 7:
 8:    //Method to print information on the screen
 9:    void Printout() {
10:        System.out.println("Name:           " + name);
11:        System.out.println("Account Number: " + accountNumber);
12:        System.out.println("Balance:
      $XXXXXX, Sorry that is classified");
13:    }
14:
15:    public static void main(String argv[]) {
16:        //Create an instance of First
17:        First f = new First();
18:
19:        //Add data to the variables in class First
20:        f.name = "John Smith";
21:        f.accountNumber = 235412345;
22:        f.balance = 25;
23:
24:        //Draw the top border
25:        for (int i = 0; i < 40; i++)
26:            System.out.print("--");
27:
28:        //Title
29:        System.out.println("      INFORMATION");
30:
31:        //Call method to print the information
32:        f.Printout();
33:
34:        //Draw bottom border
35:        for (int i = 0; i < 40; i++)
36:            System.out.print("--");
37:
38:        //Ending remark
39:        System.out.println("End of printout");
40:
41:    }
42:}

Looking at Listing 8.1, you should notice some things that are familiar to you. Basically, the class First has three variables: name, accountNumber, and balance (lines 4, 5, and 6); and one method called Printout() (lines 9 through 13). However, no action takes place until line 15, which is the first line of the main() method. On line 17, an instance of class First is constructed. Then, in lines 25 and 26, the top border is an algorithm that scrolls through and draws dashes across the screen. On line 32, Printout() is invoked. Method Printout() uses the method System.out.println() (lines 10, 11, and 12). Lines 35 and 36 draw a lower border, and line 39 puts in a closing remark.

The system methods of print() and println() may be something you have seen before. However, take a closer look at System.out.print(). The class System comes from the package java.lang that is automatically imported in any Java program (be it application or applet). Table 8.1 shows a list of variables and methods that belong to the System class.

Table 8.1. The System class.Variable index

Variable NameUsage
public static PrintStream err The output stream for error messages.
Public static InputStream in The standard input stream for reading data.
Public static PrintStream out The standard output stream for printing messages.

Method Index

Method NameUsage
arraycopy (Object src, int src
Position, Object dst,
dstPosition, int len)
Copies an array.
currentTimeMillis() Returns a long that holds the value in milliseconds since January 1, 1970.
exit(int status) Exits the application with the specified status code (0 if successful).
gc() Manually invokes the garbage collector. Note that unless garbage collection is manually enabled or disabled, it is done automatically by the Java virtual machine.
getProperties() Returns a Properties class with the system properties.
getProperty (String key, String default) Returns a String with a value for the specified property. Or, returns the default if the specified property is not set.
runFinalization () Runs the finalization methods of any object pending finalization.
setProperties (Properties props) Sets the system properties based on the specified properties.

Table 8.1 shows only a partial list of all of the methods available for the System class; for a complete review, reference Chapter 32, "Package java.lang."

So where are the println() and print() methods for the System class? If you noticed in Listing 8.1, you are using the variable out that belongs to the System class. The variable out is an instance of the class PrintStream. PrintStream is part of the set of stream classes that are used in Java.

Now go ahead and compile the code for First.java by running the javac.exe on the file at the command prompt. If the executable is in the same directory as the source file, or the directory where javac.exe is located is specified in the environmental path, then you can type the following at the command prompt. Otherwise, you will need to include the directory where the javac executable is located:

javac First.java

If you typed everything correctly, then you should see something like Figure 8.3.

Figure 8.3 : Compiling the First application.

Note
When compiling a source code file, the executable compiled file will retain the same name as the source file but have an extension of .class. The compiled file, unless otherwise specified, will be dropped in the same directory where the source file is located.

Now you can run the application by using the Java interpreter (called java.exe) from the command prompt in a very similar fashion to which you compiled it:

java First

When the execution is finished, you should see something similar to Figure 8.4.

Figure 8.4 : Running the First application.

Note
When interpreting files, you do not need to specify the extension of the source code file, which is always .class.

Note
Now that you have compiled your first Java application, you may be wondering what you need to distribute it. Basically, all that you need to distribute a Java application is the compiled class file (that is, the file javac creates with the .class extension) and an interpreter.

Importing Other Packages to Your Java Applications

Looking back at Table 8.1, imagine that you wanted to create a very simple Java application that would display the date. One method available to you is the currentTimeMillis(). The currentTimeMillis() returns a 64-bit integer long representing the number of seconds since January 1, 1970. In your text editor, go ahead and key in Listing 8.2 and save it as DisplayDate.java.


Listing 8.2. The code for DisplayDate.java.
 1:public class DisplayDate {
 2:
 3:    public static void main(String argv[]) {
 4:
 5:        //Draw the top border
 6:        for (int i = 0; i < 40; i++)
 7:            System.out.print("--");
 8:
 9:        //Display the time
10:            System.out.println("Milliseconds since January 1, 1970:  
   " + System.currentTimeMillis());
11:
12:        //Draw the bottom border
13:        for (int i = 0; i < 40; i++)
14:            System.out.print("--");
15:
16:        //Closing remark
17:        System.out.println("End of printing");
18:
19:    }
20:}

Reviewing Listing 8.2, you see that, just as in the first example, there is a top border created in lines 6 and 7. The actual method currentTimeMillis() is located inside System.out.println() on line 10. A bottom border is drawn on lines 13 and 14 with a closing remark on line 17.

Compile this example by typing the following at the command prompt (or something similar):

javac DisplayDate.java

Once it has successfully compiled, run it by typing the following at the command prompt, and you should see something similar to Figure 8.5:

Figure 8.5 : Running the DisplayDate application.

java DisplayDate

Obviously, this is not very useful for figuring out what today's date is. You would need to write several fairly complex algorithms to turn that huge number into a more useful format-something not very practical in the real world.

Note
The number displayed in Figure 8.5 is very large and growing at a fast rate. One might guess that it will overflow and become inaccurate. However, the integer data type that holds it is a long, which is a 64-bit signed integer and should be accurate well past the year 200,000,000, so there is no immediate cause for worry.

This number is used as an internal clock by the system, and it may not be useful for giving you the date. However, it is useful in some cases for time-driven software. For example, imagine you had a piece of software that you wanted to expire in 30 days. You would stamp that number inside your program with the date it was installed on the user's system, and calculate 30 days worth of milliseconds before shutting off your program.

Returning to a more common issue: What if you wanted to display today's date to the user of your application? Java has a built-in class in the package java.util called Date that gives you this functionality. However, if you tried to use the class Date now, you would immediately notice that java.util is not one of the default packages automatically imported to your application. Hence, you will need to import it manually. The syntax for importing a package or class is the same for applications and applets alike and by this point should not be anything new to you. At the very beginning of your source code class file, you state the class, classes, or packages you want to have imported and precede each one of them by the keyword import:

import java.util.Date;

Now, based on this snippet of code, your class will have access to all the non-private members of the Date class. Once again, this should be nothing new to you, and you will definitely have a chance to work with it more in the coming chapters.

Listing 8.3 shows the DisplayDate2.java application that has imported the java.util.Date class and uses some of the methods contained in it. For more information on all of the methods available to you in the Date class, see Chapter 34, "Package java.util."


Listing 8.3. The code for DisplayDate2.java.
 1:import java.util.Date;
 2:
 3:public class DisplayDate2 {
 4:
 5:    Date todaysDate = new Date();
 6:
 7:    public static void main(String argv[]) {
 8:
 9:        //Draw the top border
10:        for (int i = 0; i < 40; i++)
11:            System.out.print("--");
12:
13:        //Create an instance of DisplayDate2
14:        DisplayDate2 d = new DisplayDate2();
15:
16:        //Display the Date
17:        System.out.println("Today's Date: " + d.todaysDate);
18:
19:        //Draw the bottom border
20:        for (int i = 0; i < 40; i++)
21:            System.out.print("--");
22:
23:        //Closing remark
24:        System.out.println("End of printing");
25:
26:    }
27:}

Looking at the preceding code, you can see that in line 5 you are declaring a variable called todaysDate from Date, and by using the constructor in this format, you are in fact retrieving the date and time. Once again in lines 10, 11, 20, and 21, you are building the upper and lower borders for the application. Then, in line 14, you are creating an instance d of the DisplayDate2 class; and on line 17 using System.out.println(), you are actually printing it out. Overall, this application is fairly simple and the date being printed out is much easier to understand. Compile and run the program, and you should see something similar to Figure 8.6.

Figure 8.6 : Running the DisplayDate2 application.

Importing is an integral part of the Java experience whether it is with applications or applets-it's something which with every Java developer should become familiar.

Using argv[] to Pass Command-Line Arguments

One of the attributes of an application is the ability to pass a command-line argument to it. For example, imagine you had a program to which you wanted to pass a word. The following shows what you would type when you run the application:

java ABClass test

Where does the argument go? It goes to the array of strings you declared in the main() method, in this case, argv[].

Tip
You can name the array of strings anything you want. Typically, the most common names used are argv[] (which comes from C), arg[], or even args[].

Basically, the input parameter will put each of the arguments passed to it in a separate index in the array. Hence, you can have more than one argument passed in a single session:

java ABClass test 2

In the preceding example, there are two arguments. The first argument, test, in this case will go into argv[0], and the second 2 will be placed in argv[1].

Note
Unlike C/C++, the name of the application is not stored as the first item in the argv[] array.

The last thing to note about passing arguments is what to do if you want to pass two or more items as one argument. This can be accomplished by putting the entire argument into quotation marks. In the following snippet of code, you have only two arguments, Ford Mustang and Honda Civic:

java ABClass "Ford Mustang" "Honda Civic"

Now move forward and create a runnable example of how to pass parameters to a Java application.


Listing 8.4. The code for SayHello.java.
 1:public class SayHello {
 2:
 3:    public static void main(String argv[]) {
 4:
 5:        //Draw the top border
 6:        for (int i = 0; i < 40; i++)
 7:            System.out.print("--");
 8:
 9:        //Check to see if no argument was passed
10:        if (argv.length == 0) {
11:            System.out.println("Please enter your name!");
12:            System.out.exit(0);
13:        }
14:
15:        // Loop through and say hello to everyone
16:        for (int i = 0; i < argv.length; i++)
17:        System.out.println("Hello " + argv[i]);
18:
19:        //Draw the bottom border
20:        for (int i = 0; i < 40; i++)
21:            System.out.print("--");
22:
23:        //Closing Remark
24:        System.out.println("End of printing");
25:    }
26:}

When you look at Listing 8.4, nothing should be new to you except for the argv.length used in line 10 and line 16, and System.out.exit(). The argv.length variable contains the value for the number of elements utilized in the specified array, which in this case is argv[]. The System.out.exit() is used to end execution of the application. Other than that, lines 10 to 13 check to see if the length of the array is 0; if true, then there were no arguments passed to it. The for loop located in lines 16 through 17 loops through the length of the array and then prints it out.

Now go ahead and compile it by typing the following at the command prompt:

javac SayHello.java

Next, go ahead and run it by typing the following:

java SayHello Dan Bill "John Smith"

Figure 8.7 shows the command prompt displaying the output for the preceding command. As you can see in the figure, it says hello to each of the three arguments passed to it.

Figure 8.7 : Running the SayHello application.

Now, experiment by not passing any parameters to the application by typing the following:

java SayHello

Figure 8.8 shows what you should see as the output of the application.

Figure 8.8 : Running the SayHello application without arguments.

Summary

In this chapter, you learned about the similarities and differences between applets and applications and where applications reside in the overall Java paradigm. Applications provide the advantages of being able to link native code, as well as more flexibility with security than their applet counterparts. Also, the anatomy of Java applets is vastly different, with applications being designed around the more traditional (that is, C/C++) format of utilizing the main() method. The other half of the chapter gave several examples of passing arguments to Java applications.

Probably the last topic to note before leaving this chapter is the fact that all of the examples in this chapter were based strictly on console-based applications. In Chapter 17, "Programming the User Interface," when you are introduced to the AWT (Abstract Window Toolkit), you will be able to create applications that contain windows, dialogs, text fields, and all of the other components that make up a modern GUI-based program.