Chapter Nine

Getting Started with Java: Compiling, Interpreting, Executing

9.1 COMPILED LANGUAGES

As we have seen in our work with Maple, a computer is an incredibly powerful and helpful device, when it does what you want. Maple is a fairly easy way to tell the computer what to do and that is why we started with it; you enter a command and Maple responds. If Maple cannot understand your command, or if its response is not what you like, then you just keep changing the command until all is well. In this line-by-line mode with a response after each command line, Maple is acting as an interpreter. Having the immediate response of an interpreter is useful, and when it is combined with a friendly graphical user interface (GUI), as in Maple, we have a powerful environment for scientific work.

To provide you with a broader experience in scientific computing than is possible with Maple, we now look at a different approach. Rather than enter commands one at a time, we write a program containing all the commands, and then have the computer process (compile) them all in one fell swoop.

Just as you probably have found it rather rare to be able to enter many Maple commands without making at least one error, it will also be rather rare that you are able to write a long program perfectly on the first try. However, there are many rewards to be had by trying, and once you get it right it, running it can be a breeze. But not to worry, we will start you with programs to modify rather than making you start from scratch.

To understand the value of a compiled language, imagine telling a story to a bunch of friends at party in which you were restricted to speaking only one sentence at a time, and could not continue your story until someone else responded to each of your sentences. Even though you might be able to get through your story, you could probably weave a better tale if you did not have to stop all the time. Likewise it is with a compiled approach to computing. Though it may take

image

Figure 9.1 Steps in compiling and executing a Java program.

some more skill and time to weave a long program, you should be able to make it do exactly what you want, in exactly the way you want it done. And if the program gets used more than once, for instance to analyze different data sets, you do not have to repeat the process.

Here are some reasons for using Java as your first compiled language:

1.  Java is the closest a computer language has ever come to being universal in syntax and execution, secure, and highly flexible.

2.  Java is modern in structure, much like C and C++, and essential for computing on the World Wide Web.

3.  Java requires the user to be specific about the type of variables declared (strongly type-cast) and is very careful about the precision of mathematical functions. This helps a student learn the proper handling of floating-point variables (especially important in scientific computing).

4.  Java incorporates the modern, and possibly best, view towards programming known as object-oriented programming. C++ is also object-oriented but harder to learn.

5.  Java has automatic “garbage collection”; that is, it automatically frees up sections of computer memory once your program stops using them. In C, you must do this yourself (a pain).

6.  In our view the error-handling capability of Java, both during compilation and execution, is excellent. It is demanding that its grammar be followed (a good thing) and informative when it is not.

7.  Finally, Java is exciting. Much of the excitement has arisen from Java’s ability to do Web computing and from the availability of many classes (prepared utility programs to be incorporated into your program).

We have not said that we like Java because it is fast. Compared to Fortran and C, Java is slow, although it has the promise of being much faster. However, since modern computers are so fast, its speed will not affect you until you get into large projects. Likewise, there are fewer scientific libraries of programs for Java than for Fortran and C. However, the availability of libraries is also improving, spurred on, in part, from the developers not having to have a different library for each operating system.

Listing 9.1 Area.java

image

9.2 JAVA PROGRAM PIECES

Whether simple or complex, developing Java programs requires two basic elements. These are indicated in Figure 9.1. One is a source file that you have written in Java and has a name ending with .java. The other is the executable file that the computer compiles for only computers to read, and has a name ending with .class. For instance, in Listing 9.1 we give the contents of a source file containing a simple program Area.java that calculates the area of a circle. There are a number of actions involved in order for you to convert Area.java into something a computer will understand:

1.  You issue a command to compile the Java source code from within a shell (a command-line interpreter). You know that you are “in” a shell by the command-line prompt, which may contain a > or a %, or something containing the name of the directory/folder in which you are located.

2.  The conversion of your program into an executable file is done with the Java compiler at the shell prompt (the second step in Figure 9.1):

image

When we illustrate commands like the one above, the first field of characters (>) is the shell’s prompt, the second field, in monospaced bold type, is the command that you enter, and the rightmost field is a comment to you that should not be entered.

3.  For these commands to work you must issue the javac command from within the directory in which the file Area.java is stored.1 If the compilation was successful and you get no error messages, Java will have written another file in the same directory ending with the extension .class. In our example, Area.class.

4.  In Java terminology, the compiled program in the .class file contains byte code. The term byte indicates that the code is compiled to the byte level, and the term code is used synonymously with the word “program.” Java’s universality means that this same .class file runs on any operating system, be it Unix, Windows, or Mac. In other compiled languages like Fortran and C, the compiled code contains commands that only one particular computer is able to execute, but it does so immediately. In Java, the compiled code is universal, yet another, internal, step is required before execution.

5.  The last processing step in Figure 9.1 is executing or running your program:2

image

When we issue this execution command java, the .class extender to Area is left off. Java just needs to know that Area is the name of the class for it to run the program Area.class. If you actually entered Area.class or Area.java as the program to run, you would get an error message. Go ahead and try java Area.class, it does no harm.

9.3 ENTERING AND RUNNING YOUR FIRST PROGRAM

As a general rule, you will not learn to compute just by reading about it. You must do what is necessary to get a program running and giving correct answers before you understand it. Accordingly, before we try to explain what is inside a Java program, let us get some experience with the steps we have outlined so far.

In the code Listing 9.1 is the Java source code for the program Area.java. The line numbers on the left are there to help explain the program to you; do not enter the line numbers in your program. The lines beginning with a //, or between /* and */, are comments not read by Java. You do not need to enter these comments into your program, but they do help with understanding and documentation, and you are free to put whatever you want there.

1.  Use a text editor3 to enter Area.java into a file named Area.java in the directory for your work. By “enter” we mean key the program in rather than cut and paste it. You may view this as mindless clerical work, but reading and looking at what you are entering helps make this foreign language seem less alien.

2.  After you have entered the entire program, Save it into a file named Area.java in your personal directory.

3.  Open a shell in your directory and compile Area.java:

image

We remind you: the > here is the computer’s prompt to you; the command you enter is in bold monospaced font, and the last field is a comment, not to be entered.

4.  If compilation is successful, you will be told nothing (you only get spoken to when you do something wrong). However you can check that a file Area.class was created by listing all the files, with creation times, in your working directory:

image

5.  If you do have to correct some error (presumably typographical since you are just coping over a running program), open your Area.java in an editor and fix it. It is a good idea to keep the editor open in a separate window while you compile in the shell’s window. Then Save Area.java in the same directory where you are doing the compiling and try compiling again.

6.  Get into the habit of saving your files often, and sometimes as backup copies. Saving writes a copy to the hard disk for storage, while closing the file removes it from the grasp of the editor, without necessarily saving it.

7.  If you like looking where you should not, use your editor to open and look at the Area.class file. Inasmuch as this file is not meant for human comprehension, what you see will not be illuminating. Alternatively, these files are viewable from the shell:

image

8.  We find ourselves more patient waiting for the computer to do its work if we know what the computer is doing (this also alleviates anxieties that we have done something wrong). On this account we recommend that you include the -verbose option in your commands. We may leave it off in this book to keep things short, but it is fun to include it:

image

9.  Check again that you have created the byte code version of your Java program, namely, that there is a file Area.class:

image

10.  As we see from Figure 9.1, once we have compiled code in Area.class, we get the computer to execute or run it by issuing the java command (no c) at the prompt with just the class name:

image

You should get output of the form

Program number = 1

Radius = 1.0

Circumference = 6.283186

Area = 3.141593

11.  Now that you have a program that is running, check that it is actually doing as you intended by changing a line in it and seeing how the results change. In particular, try assigning a value to the variable radius:

6 radius = 1.;

12.  Use your editor to change this line to radius = 10.;, being careful not to leave out the semicolon “ ;” at the end of the line.

13.  Save the modified Java source code in the file Area.java.

14.  Compile the modified file, correcting any errors if necessary.

15.  Execute the new Area.class file with the command java Area, and check that you get 100 π as the area.

16.  To see how Java responds to not doing things correctly, be adventurous and try below some unconventional variations on the theme:

image

9.4 LOOKING INSIDE AREA.JAVA

We now look at Area.java to get some idea of how a program goes about its business. Though a simple program, it is not trivial in that it contains a number of important parts. Admittedly it is hard to understand at first all that is going on; be patient, after seeing them a few times it begins to make more sense.

// Comments and /* Comments */ At the top of Area.java is a // and some information about the program. Text following the // is a comment unread by Java and placed there as information for the user. The // comment may be placed on a line by itself, or after some Java statements. Multiline comments start with a /* and end with a */. They too are ignored by Java. We encourage the use of comments and blank lines to make code clearer. Nevertheless, we are frugal in our examples in order to space printed space.

public class Area This line declares the name of the class to be Area. You may think of the term class as the name of our program.4 Remember that this is exactly the same named used for the file Area.java containing the Java source. In fact, if the two do not agree, then Java will complain. The public on line 2 indicates that this class may be read by other programs. While speaking of area, notice on line 8 the statement area = radius * radius * PI. Here area is the name of a variable, and since Java is case sensitive, Java treats it as a completely different name from the class name Area.

public static void main(String[] argv) Line 3 contains the important word main and means that the main method is to follow. A class usually contains a number of methods, the term method denoting a subprogram that behaves like a mathematical function. It is called a “method” to indicate that it is a method for handling data or variables.

Every Java program that runs directly on a computer, that is, not via a Web browser, must contain a main method as the place where execution begins. This simple program contains only one method, the main method. The body of the main method is made up of all the lines of code between the first open brace { and the last close brace }. Usually the main method is used as the control unit or administrator for a program; it does not do much in the way of work itself, but instead calls other methods to get the computation done and then collects and organizes their results.

It is probably best for first-time readers to just accept the phrase public static void main(String[] argv) as the way to declare a main method, and ignore for now our explanation of what the modifiers and arguments to main mean.

Nevertheless, we now give some explanation for completeness and for later-time readers.

The modifier static before main indicates that main is a static method, and not dynamic like an object. We talk about objects in Chapters 16 and 18, and suggest you ignore it for now. The modifier void before main indicates the type of output produced by main, in this case nothing. Likewise, the parentheses in main(String[] argv) contain the input or arguments supplied to main. In this case there is a single argument named argv and it is a String. The square brackets [ ] indicate that argv is an array, that is, a subscripted variable.

double radius, circum, …; int modelN = 1; Before you are permitted to use a variable in Java, you must declare its name and the type of variable it is. This creates instances or records of them so that they may be used later. The first line declares the variables r, area and PI to be double, that is, double precision. The next line declares the variable modelN to be an int, that is, an integer. (We describe the various data types in the next chapter).

Instead of assigning values later, lines 4 and 5 serve double duty by assigning initial values to the variables PI and modelN. Inspect how in both of these lines there is first a data type (double or int) and then a series of one or more variables that will be stored with this data type. Any number of variables are permitted on these lines, although it is probably best to add additional declaration lines rather than have one line so long that its end gets hidden beyond the edge of the screen. A semicolon; is used to end these two statements, as is true for most “action type” statements in Java.

radius = 1.; Lines 6, 7, and 8 are assignment statements. They compute the numerical value of whatever expression is on the RHS of = and assign that number to the variable named on the LHS of =. Here, “assign” means to store a numerical value in the memory location reserved for that variable. (This is the same as the assignment operator: = in Maple, except Java deals only with numerical values.)

Arithmetical operations are denoted by the standard +, -, *, and / symbols. However, the symbol ˆ, often used for exponentiation, is used for a logical operation xor in Java. Instead, use the power function in the Math class, Math.pow(x,2). In this example we squared the variable radius by simply using radius * radius, but we could also have said Math.pow(radius,2).

System.out.println(. . .) ; These lines look worse than they really are and may be used as given until you know better. If you learn to read the System.out.println part backwards, you could believe that it says to print a line out using Java’s (the System’s) methods to do this. The periods in the command denote the access route. Starting from the top level class, the System class, we then access a subclass out and one of its methods, the println(String s) method. (As an example of another such object-oriented method access, say you make a class MyClass with a method myMethod(). If you wish to access this method, then call MyClass.myMethod();.) Getting back to these output lines, the argument (“Program Number = “ + modelN) means take the string Program Number = and append another string containing the numerical value of the variable modelN to the end of it. The appending is done by the + modelN part. Likewise, the output on line 11 starts with a string Radius = and appends the numerical value of radius to it. Once these strings are built up (concatenated), they get printed out to your screen, each on a new line. If you do not want Java to place your output on a new line, but instead to continue with the last line, then you would leave off the ln part:

System.out.print(” Program Number = “ + modelN);

You are allowed to make the string that gets printed as long as you like by concatenating more and more substrings to it. To cite an instance, on line 13

System.out.println(“Radius = “ + radius +”, Area = “ + area);

after the value of radius is added to the string, we add in the string “, Area =, “ and then add on the value of area after that. (When we say “add on the value of,” what really is happening is that Java is converting a double to a string, and then adding that string to the end of the previous string).

9.5 KEY WORDS

assignment statement

byte code

class

comments

compile

execution

garbage collection

interpreter

methods

objects

program

shell

source file/code

type-cast

text editor

print

string

main method

running

9.6 SUPPLEMENTARY EXERCISES

1.  Modify Area.java into a new program Volume.java that calculates the volume of a liquid in a spherical tank of radius R, when the liquid is a height H above the bottom of the tank. We have already studied this problem with Maple in Chapter 8, where we derived that the volume V = πH2(R-H/3). Make sure to test your program for H = 0, R, and 2R, namely, for an empty, a half-full, and a full tank.

2.  Explain in just a few words:

a.  what the Java interpreter does;

b.  what the Java compiler does;

c.  how Java differs from an operating system;

d.  what is a shell.

1If you are using a programming environment package such as Code Warrior, some of this will be done automatically for you. Nevertheless, it is a good idea to check the location and modification dates of the files you create and use.

2In a strict sense this is interpreting, because Java executes the Area.class file one line at a time. However, most modern Java installations actually recompile the byte code into a completely compiled object code, and then run the recompiled code. In any case, as far as you are concerned Java will follow the commands in your program from top to bottom.

3An editor is a program like Notepad on a Windows PC, or nedit or Xemacs on Unix. Word processing programs like Wo r d or Word Perfect are possible, but you must remember to save the file as Te x t to avoid control characters that will confuse the compiler.

4In a formal sense, a class is a collection of data (variables) and methods (functions) that act on those data. In the present case, our class file has only the main method.

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

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