Monday, 11 May 2015

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.javaand 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 Firsthas 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 Firstis 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 Systemclass.Variable index


Variable NameUsage
public static PrintStream errThe output stream for error messages.
Public static InputStream inThe standard input stream for reading data.
Public static PrintStream outThe 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; "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 outthat belongs to the Systemclass. 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.javaby running the javac.exeon the file at the command prompt. If the executable is in the same directory as the source file, or the directory where javac.exeis 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
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
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
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.utilcalled Date that gives you this functionality. However, if you tried to use the class Datenow, you would immediately notice that java.utilis 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 Dateclass. 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.javaapplication that has imported the java.util.Dateclass and uses some of the methods contained in it. 

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 todaysDatefrom 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 dof the DisplayDate2 class; and on line 17 using System.out.println(), you are actually printing it out. 

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 forloop 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"

No comments:

Post a Comment