I had to replace < with [ and > with ] to post this.
You can run Java programs on a wide variety of computers using a range of operating systems. Your Java programs will run just as well on a PC running Windows 95/98/NT/2000/XP as it will on Linux or a Sun Solaris workstation. This is possible because a Java program does not execute directly on your computer. It runs on a standardized hypothetical computer that is called the Java virtual machine or JVM, which is emulated inside your computer by a program.
A Java compiler converts the Java sourcecode that you write into a binary program consisting of byte codes. Byte codes are machine instructions for the Java virtual machine. When you execute a Java program, a program called the Java interpreter inspects and deciphers the byte codes for it, checks it out to ensure that it has not been tampered with and is safe to execute, and then executes the actions that the byte codes specify within the Java virtual machine. A Java interpreter can run standalone, or it can be part of a web browser such as Netscape Navigator or Microsoft Internet Explorer where it can be invoked automatically to run applets in a web page.
Because your Java program consists of byte codes rather than native machine instructions, it is completely insulated from the particular hardware on which it is run. Any computer that has the Java environment implemented will handle your program as well as any other, and because the Java interpreter sits between your program and the physical machine, it can prevent unauthorized actions in the program from being executed.
In the past there has been a penalty for all this flexibility and protection in the speed of execution of your Java programs. An interpreted Java program would typically run at only one tenth of the speed of an equivalent program using native machine instructions. With present Java machine implementations, much of the performance penalty has been eliminated, and in programs that are not computation intensive - which is usually the case with the sort of program you would want to include in a web page, for example - you really wouldn't notice this anyway. With the JVM that is supplied with the current Java 2 System Development Kit (SDK) available from the Sun web site, there are very few circumstances where you will notice any appreciable degradation in performance compared to a program compiled to native machine code.
Java Program Development
There are a number of excellent professional Java program development environments available, including products from Sun, Borland and Symantec. These all provide very friendly environments for creating and editing your sourcecode, and compiling and debugging your programs. These are powerful tools for the experienced programmer, but for learning Java using this book, I recommend that you resist the temptation to use any of these, especially if you are relatively new to programming. Instead, stick to using the Java 2 SDK from Sun together with a suitable simple editor for creating your sourcecode. The professional development systems tend to hide a lot of things you need to understand, and also introduce complexity that you really are better off without while you are learning. These products are intended primarily for knowledgeable and experienced programmers, so start with one when you get to the end of the book.
You can download the SDK from Sun for a variety of hardware platforms and operating systems, either directly from the Sun Java web site at
http://java.sun.com (for Windows, Solaris, and Linux operating systems), or from sites that you can link to from there. The SDK we are going to use is available from
http://java.sun.com/j2se/1.4. For instance a version of the SDK for Mac OS is available from
http://devworld.apple.com/java/. There is one aspect of terminology that sometimes causes confusion - the SDK used to be known as the JDK - the Java Development kit. If you see JDK this generally means the same as SDK. When you install the Java 2 SDK, you will see the old terminology survives in the name of the root directory where the SDK is installed, currently /jdk1.4.
I would urge you to install the SDK even if you do use one or other of the interactive development environments that are available. The SDK provides an excellent reference environment that you can use to check out problems that may arise. Not only that, your programs will only consist of the code that you write plus the classes from the Java libraries that you use. Virtually all commercial Java development systems provide pre-built facilities of their own to speed development. While this is very helpful for production program development, it really does get in the way when you are trying to learn Java.
A further consideration is that the version of Java supported by a commercial Java product is not always the most recent. This means that some features of the latest version of Java just won't work. If you really do prefer to work with a commercial Java development system for whatever reason, and you have problems with running a particular example from the book, try it out with the SDK. The chances are it will work OK.
To make use of the SDK you will need a plain text editor. Any editor will do as long as it does not introduce formatting codes into the contents of a file. There are quite a number of shareware and freeware editors around that are suitable, some of which are specific to Java, and you should have no trouble locating one. I find the JCreator editor is particularly good. There's a free version and a fee version with more functionality but the free version is perfectly adequate for learning. You can download a free copy from
http://www.jcreator.com. A good place to start looking if you want to explore what is available is the
http://www.download.com web site.
Installing the SDK
You can obtain detailed instructions on how to install the SDK for your particular operating system from the Sun web site, so I won't go into all the variations for different systems here. However, there are a few things to watch out for that may not leap out from the pages of the installation documentation.
First of all, the SDK and the documentation are separate and you install them separately. The SDK for Windows is distributed as a .exe file that you just execute to start installation. The documentation for the SDK consists of a large number of HTML files structured in a hierarchy that are distributed in a ZIP archive. You will find it easier to install the SDK first, followed by the documentation. If you install the SDK to drive C: under Windows, the directory structure shown in the diagram will be created.
The jdk1.4 directory in the diagram is sometimes referred to as the root directory for Java. In some contexts it is also referred to as the Java home directory. If you want the documentation installed in the hierarchy shown above, then you should now extract the documentation from the archive to the jdk1.4 directory. This corresponds to C:\jdk1.4 if you installed the SDK to your C: drive. This will create a new subdirectory, docs, to the jdk1.4 root directory, and install the documentation files in that. To look at the documentation you just open the index.html file that is in the docs subdirectory.
You don't need to worry about the contents of most of these directories, at least not when you get started, but you should add the path for the jdk1.4\bin directory to the paths defined in your PATH environment variable. That way you will be able to run the compiler and the interpreter from anywhere without having to specify supplying the path to it. If you installed the SDK to C:, then you need to add the path C:\jdk1.4\bin. A word of warning - if you have previously installed a commercial Java development product, check that it has not modified your PATH environment variable to include the path to its own Java executables.
If it has, when you try to run the Java compiler or interpreter, you are likely to get the versions supplied with the commercial product rather that those that came with the SDK. One way to fix this is to remove the path or paths that cause the problem. If you don't want to remove the paths that were inserted for the commercial product, you will have to use the full path specification when you want to run the compiler or interpreter from the SDK. The jre directory contains the Java Runtime facilities that are used when you execute a Java program. The classes in the Java libraries are stored in the jre\lib directory. They don't appear individually though. They are all packaged up in the archive, rt.jar. Leave this alone. The Java Runtime takes care of retrieving what it needs from the archive when your program executes.
The CLASSPATH environment variable is a frequent source of problems and confusion to newcomers to Java. The current SDK does NOT require CLASSPATH to be defined, and if it has been defined by some other Java version or system, it is likely to cause problems. Commercial Java development systems and versions of the Java Development Kit prior to 1.2 may well define the CLASSPATH environment variable, so check to see whether CLASSPATH has been defined on your system. If it has and you no longer have whatever defined it installed, you should delete it. If you have to keep the CLASSPATH environment variable - maybe because you want to keep the system that defined it or you share the machine with someone who needs it - you will have to use a command line option to define CLASSPATH temporarily whenever you compile or execute your Java code. We will see how to do this a little later in this chapter.
Extracting the Sourcecode for the Class Libraries
The sourcecode for the class libraries is included in the archive src.zip that you will find in the jdk1.4 root directory. Browsing this source can be very educational, and it can also be helpful when you are more experienced with Java in giving a better understanding of how things works - or when they don't, why they don't. You can extract the source files from the archive using the Winzip utility or any other utility that will unpack .zip archives - but be warned - there's a lot of it and it takes a while!
Extracting the contents of src.zip to the root directory \jdk1.4 will create a new subdirectory, src, and install the sourcecode in subdirectories to this. To look at the sourcecode, just open the .java file that you are interested in, using any plain text editor.
Compiling a Java Program
Java sourcecode is always stored in files with the extension .java. Once you have created the sourcecode for a program and saved it in a .java file, you need to process the source using a Java compiler. Using the compiler that comes with the JDK, you would make the directory that contains your Java source file the current directory, and then enter the following command:
javac -source 1.4 MyProgram.java
Here, javac is the name of the Java compiler, and MyProgram.java is the name of the program source file. This command assumes that the current directory contains your source file. If it doesn't the compiler won't be able to find your source file. The -source command line option with the value 1.4 here tells the compiler that you want the code compiled with the SDK 1.4 language facilities. This causes the compiler to support a facility called assertions, and we will see what these are later on. If you leave this option out, the compiler will compile the code with SDK 1.3 capabilities so if the code uses assertions, these will be flagged as errors.
If you need to override an existing definition of the CLASSPATH environment variable - perhaps because it has been set by a Java development system you have installed, the command would be:
javac -source 1.4 -classpath . MyProgram.java
The value of CLASSPATH follows the -classpath specification and is just a period. This defines just the path to the current directory, whatever that happens to be. This means that the compiler will look for your source file or files in the current directory. If you forget to include the period, the compiler will not be able to find your source files in the current directory. If you include the -classpath . command line option in any event, it will do no harm.
Note that you should avoid storing your source files within the directory structure that was created for the SDK, as this can cause problems. Set up a separate directory of your own to hold the sourcecode for a program and keep the code for each program in its own directory.
Assuming your program contains no errors, the compiler generates a byte code program that is the equivalent of your source code. The compiler stores the byte code program in a file with the same name as the source file, but with the extension .class. Java executable modules are always stored in a file with the extension .class. By default, the .class file will be stored in the same directory as the source file.
The command line options we have introduced here are by no means all the options you have available for the compiler. You will be able to compile all of the examples in the book just knowing about the options we have discussed. There is a comprehensive description of all the options within the documentation for the SDK. You can also specify the -help command line option to get a summary of the standard options you can use.
If you are using some other product to develop your Java programs, you will probably be using a much more user-friendly, graphical interface for compiling your programs that won't involve entering commands such as that shown above. The file name extensions for your source file and the object file that results from it will be just the same however.
Executing a Java Application
To execute the byte code program in the .class file with the Java interpreter in the SDK, you make the directory containing the .class file current, and enter the command:
java -enableassertions MyProgram
Note that we use MyProgram to identify the program, NOT MyProgram.class. It is a common beginner's mistake to use the latter by analogy with the compile operation. If you put a .class file extension on MyProgram, your program won't execute and you will get an error message:
Exception in thread "main" java.lang.NoClassDefFoundError: MyProgram/class
While the compiler expects to find the name of your source file, the java interpreter expects the name of a class, which is MyProgram in this case, not the name of a file. The MyProgram.class file contains the MyProgram class. We will explain what a class is shortly.
The enableassertions option is necessary for SDK1.4 programs that use assertions, but since we will be using assertions once we have learned about them it's a good idea to get into the habit of always using this option. You can abbreviate the -enableassertions option to -ea if you wish.
If you want to override an existing CLASSPATH definition, the option is the same as with the compiler. You can also abbreviate -classpath to -cp with the Java interpreter, but strangely, this abbreviation does not apply to the compiler. Here's how the command would look:
To execute your program, the Java interpreter analyzes and then executes the byte code instructions. The Java virtual machine is identical in all computer environments supporting Java, so you can be sure your program is completely portable. As we already said, your program will run just as well on a Unix Java implementation as it will on that for Windows 95/98/NT/2000/XP, for Solaris, Linux, OS/2, or any other operating system that supports Java. (Beware of variations in the level of Java supported though. Some environments, such as the Macintosh, tend to lag a little, so implementations for Java 2 will typically be available later than under Windows or Solaris.)
Executing an Applet
Note that the Java compiler in the SDK will compile both applications and applets. However, an applet is not executed in the same way as an application. You must embed an applet in a web page before it can be run. You can then execute it either within a Java 2-enabled web browser, or by using the appletviewer, a bare-bones browser provided as part of the SDK. It is a good idea to use the appletviewer to run applets while you are learning. This ensures that if your applet doesn't work, it is almost certainly your code that is the problem, rather than some problem in integration with the browser.
If you have compiled an applet and you have included it in a web page stored as MyApplet.html in the current directory on your computer, you can execute it by entering the command:
appletviewer MyApplet.html
So how do you put an applet in a web page?
The Hypertext Markup Language
The HyperText Markup Language, or HTML as it is commonly known, is used to define a web page. If you want a good, compact, reference guide to HTML, I recommend the book Instant HTML Programmer's Reference (Wrox Press, ISBN 1-861001-56-8). Here we will gather just enough on HTML so that you can run a Java applet.
When you define a web page as an HTML document, it is stored in a file with the extension .html. An HTML document consists of a number of elements, and each element is identified by tags. The document will begin with
. These delimiters,
, are tags, and each element in an HTML document will be enclosed between a similar pair of tags between angle brackets. All element tags are case insensitive, so you can use uppercase or lowercase, or even a mixture of the two, but by convention they are capitalized so they stand out from the text. Here is an example of an HTML document consisting of a title and some other text:
[ht ml]
[head]
[title]This is the title of the document[/title]
[/head]
[body]
You can put whatever text you like here. The body of a document can contain
all kinds of other HTML elements, including [B]Java applets[/B]. Note how each
element always begins with a start tag identifying the element, and ends with
an end tag that is the same as the start tag but with a slash added. The pair
of tags around 'Java applets' in the previous sentence will display the text
as bold.
[/body]
[/ht ml]
There are two elements that can appear directly within the [html] element, a [head] element and a [body] element, as in the example above. The [head] element provides information about the document, and is not strictly part of it. The text enclosed by the [title] element tags that appears here within the [head] element, will be displayed as the window title when the page is viewed.
Other element tags can appear within the [body] element, and they include tags for headings, lists, tables, links to other pages and Java applets. There are some elements that do not require an end tag because they are considered to be empty. An example of this kind of element tag is [hr/], which specifies a horizontal rule, a line across the full width of the page. You can use the [hr/] tag to divide up a page and separate one type of element from another. You will find a comprehensive list of available HTML tags in the book I mentioned earlier.
Adding an Applet to an HTML Document
For many element tag pairs, you can specify an element attribute in the starting tag that defines additional or qualifying data about the element. This is how a Java applet is identified in an [applet] tag. Here is an example of how you might include a Java applet in an HTML document:
[ht ml]
[he ad]
[title] A Simple Program [/title]
[/he ad]
[body]
[hr/]
[ap plet code = "MyFirstApplet.class" width = 300 height = 200 ]
[/applet]
[hr/]
[/body]
[/ht ml]
The two shaded lines between tags for horizontal lines specify that the byte codes for the applet are contained in the file MyFirstApplet.class. The name of the file containing the byte codes for the applet is specified as the value for the code attribute in the [applet] tag. The other two attributes, width and height, define the width and height of the region on the screen that will be used by the applet when it executes. These always have to be specified to run an applet. There are lots of other things you can optionally specify, as we will see. Here is the Java sourcecode for a simple applet:
import javax.swing.JApplet;
import java.awt.Graphics;
public class MyFirstApplet extends JApplet {
public void paint(Graphics g) {
g.drawString("To climb a ladder, start at the bottom rung", 20, 90);
}
}
Note that Java is case sensitive. You can't enter public with a capital P - if you do the program won't compile. This applet will just display a message when you run it. The mechanics of how the message gets displayed are irrelevant here - the example is just to illustrate how an applet goes into an HTML page. If you compile this code and save the previous HTML page specification in the file MyFirstApplet.html in the same directory as the Java applet code, you can run the applet using appletviewer from the JDK with the command:
appletviewer MyFirstApplet.html
This will display a window something like that shown below:
In this particular case, the window is produced under Windows 95/98/NT/2000. Under other operating systems it is likely to look a little different since Java 'takes on' the style of the platform on which it is running. Since the height and width of the window for the applet is specified in pixels, the physical dimensions of the window will depend on the resolution and size of your monitor.
This example won't work with Internet Explorer or Netscape Navigator as neither of these supports Java 2 directly. Let's see what can be done about that.
Making Applets Run in Any Browser
The key to making all your Java applets work with any browser is to make sure the Java 2 Plug in is installed for each browser that views any of your web pages that contain applets. Making sure that each browser that runs your applet has a Java 2 Plug-in installed is not as hard as you might imagine because you can arrange for it to be automatically downloaded when required - assuming that the computer is online to the Web at the time of course.
The Java Plug-in is a module that can be integrated with Internet Explorer (version 4.0 or later) or Netscape Navigator (version 6.0 or later) to provide full support for Java 2 applets. It supports the use of the [applet] tag on any version of Windows from Windows 95 to Windows XP, as well as Linux and Unix.
To enable automatic download of the Java 2 Plug-in with your applets, you need to add some HTML to your web page that invokes a Visual Basic script that handles the download and installation process for the plug-in. To modify our HTML to do this we just need to add one extra tag:
[ht ml]
[head]
[title] A Simple Program [/title]
[SCRIPT language="VBSCRIPT"
src="http://java.sun.com/products/plugin/1.4/autodl/autodownload.vbs"]
[/S CRIPT]
[/head]
[body]
[hr/]
[ap plet code = "MyFirstApplet.class" width = 300 height = 200 ]
[/applet]
[hr/]
[/body]
[/ht ml]
This makes use of a script that is downloaded from the Sun Java web site. If you want, you can download a copy of the script to your local machine and run it from there. In this case you will need to amend the URL for the src attribute in the [SCRIPT] to reflect where you have stored the .vbs file.