- 54 -

Java and JavaScript

IN THIS CHAPTER


A quick word before we start: We're not going to teach you how to program Java in this chapter! There's far too much material to do justice to the subject in a few pages. Instead, we'll look at what Java is and does, and some of the basic programming aspects.

What is Java? Java is a programming language developed at Sun Microsystems. Sun describes Java in press releases as "a simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high-performance, multi-threaded, and dynamic language." What does all that really mean? To start with, Java was intended to be a much simpler object- oriented language to work with than C++ or SmallTalk, both of which are large, cumbersome languages. By producing a small object-oriented language, Sun's developers also made Java simple and much less prone to bugs than are larger languages. Those are the simple and robust aspects of the language. The small size of the Java language also contributes to performance.

Java is an interpretive language, meaning that each line of source code is read by the Java interpreter and is executed on that basis, rather than as a compiled executable. Actually, that's a bit of a simplification, because Java code is pseudo-compiled to produce a binary object file, called a class file, that is non-hardware dependent and can be read by any Java system. This approach might be slower than a true compiled system, but by using a platform-neutral language (meaning there are no hardware or operating-specific instructions in the language), Java source code can execute on any system with a Java interpreter. That covers the architecture-neutral and portable aspects of Sun's description. The distributed aspect derives naturally from these points, because Java source code can be easily sent from one machine to another across a network for execution. This allows a server to send Java code to clients, making a distributed system (Java runs on the client and communicates back to the server).

Because Java can run on practically any operating system, it can take advantage of the host operating system's features, such as UNIX's capability to handle multithreading. Java by itself can be thought of as multithreaded, but the operating system contributes a lot in this regard. Finally, the security aspect of Java was one of the design principles of the development group. A secure method of transferring information from client to server and vice versa was needed, and Java was designed to fill this requirement.

To provide the client and server software components, Java is designed to have the interpretive component of the language attached to other software, most commonly a Web browser. Netscape's Navigator and Microsoft's Explorer, for example, both have the client components of Java attached (or "plugged in," in Web parlance) to the browser code. When incoming Java source code is detected, the Java interpreter starts and handles the task.

JavaScript was introduced after Java was on the market for a while. JavaScript is built into most Java-enabled Web browsers. JavaScript and Java don't have much in common, despite the name. Many people think of JavaScript as a stripped-down Java, but that is incorrect and misleading. JavaScript is more an extension of HTML coding that allows users to build interactive Web pages in a client-server system.

JavaScript has various uses that make it attractive, including the capability to tell what a user is doing. When a user leaves a page or clicks a certain button, the JavaScript client can communicate this information and start new routines. JavaScript is also ideal for writing little housekeeping tasks and for managing complex tasks, such as string handling, that are beyond HTML.

What You Need

To write Java applications, you need the Java Developer's Kit (JDK). The JDK contains all the software necessary to write, compile, and test Java applets. Besides the JDK, all you need is a Java-enabled browser to test and display your applets. Netscape Navigator's and Microsoft Explorer's latest releases all support Java, as do many other browsers. Sun developed its own Java-enabled browser called HotJava, which is available from the Sun Web site.


NOTE: You can get the JDK at many sites on the Web or through FTP. The primary location is the Sun page http://java.sun.com, although most Linux sites also contain pointers to mirrors or backup sites for the JDK. For a Java-enabled Web browser, check out both Netscape and Microsoft home pages, as well as Sun's HotJava. For other browsers and Java development tools, check the Linux sites on the Web. For FTP access to the JDK, FTP to java.sun.com and change to the directory /pub, which contains the files you need.

The Sun Java section also contains a wealth of details on Java development, lots of sample code, advice, and FAQs. A white paper on Java obtained at the same site (http://java.sun.com/ tutorial/java/index.html) is an excellent introduction to the language. The Java Developer's Kit is free if you are using it for personal reasons only, but if you plan to publish Java-based Web pages, you might need a license. Details are included with the JDK.

When installing the JDK, make sure that the path to the Java executables is in your path. Even better, link the executables to /bin. The most common errors Java programmers make while learning the language have to do with case sensitivity and class use. Java, like UNIX, is case sensitive, so developers must be careful to ensure that their code is correct. Class usage follows C++ methods, and it must be adhered to properly. A good Java book is a must for learning the language, and there are many books on learning Java.

For JavaScript, all you need is a JavaScript-enabled browser (such as Netscape Navigator 2.02 or higher), a standard ASCII editor or an editor that can save in ASCII, and a TCP/IP stack to communicate with other machines over the Internet or an intranet.

The Java Language

From the programmer's point of view, Java is a very stripped-down object-oriented (OO) language. The principles of OO programming are suitable in most cases to client-server applications, so using OO for Java made sense. By staying with OO, Java avoided the need to set up procedural language structures, all of which cause code bloat to the point that Java would not be nearly as fast. Also, by avoiding procedural language principles, Java designers can ignore many of the startup and initialization aspects of programming, again making the source code smaller and faster. Learning Java is not especially difficult. If you know an OO language such as C++, you will probably find Java easier to learn than if you've worked only in procedural languages such as C or BASIC.

Java may be an OO language, but it's not strict about it. SmallTalk, for example, is considered a pure OO language because all aspects of SmallTalk are dealt with as either objects or messages, and all data are object classes. Java doesn't go quite as far, primarily to avoid an overly large language. Java implements all the simple C data types (integers, floating points, and characters) outside of the OO method, but everything else is object-based. This is both a benefit, because it leads to smaller, faster code, and a problem, because it means you can't subclass Java data objects.

As mentioned earlier, Java is interpreted. When you develop Java applications, you write the Java code as you would with any other language, then pass it through a Java processor to produce the binary object file. The binary object file, called a class file in Java, is not directly readable, but it can be transmitted faster than the source code from which it was derived. When a Java-equipped browser receives the class file, it runs the class file through the Java interpreter, which decodes and executes the class file instructions. In one sense, Java is both a compiler and an interpreter, in much the same way as many early languages that produced pseudo-code requiring a runtime module were. The Java client that decodes the class file performs a conversion from the generic instructions contained in the class file to machine-specific instructions for the client's hardware and operating system.

Programming in the Java language takes a little while to become comfortable. The code often seems like a hybrid of C and C++, and experience with both is handy. Because Java is a fairly simple language, however, even nonprogrammers can pick it up with a little practice. The most difficult aspects of learning Java for most people are the need to understand object-oriented design and programming, and the somewhat awkward syntax requirements (these are also familiar to C and C++ programmers). For example, here's a simple Java program:

    // HelloWorldApp.java



    class HelloWorldApp {



        public static void main (String args[]){



            system.out.println("Hello World!");



        }







    }



This program (called HelloWorldApp) defines a single method called main that returns nothing (void) and consists of a single Java instruction to print the message Hello World! The first line in the code is a comment. To compile this source code into a class file, you invoke the Java compiler with the following command line:

javac HelloWorldApp.java



The compiler then grinds away and produces a class file (HelloWorldApp.class). This class file can be run in a Java-equipped browser or from the command-line client with the command

java HelloWorldApp



which instructs Java to load and execute the .class file.

As you probably expect, Java is a lot more complicated than that in real life, but if you have programmed before, you will see the similarities to other languages (especially C and C++). The Java language is quite rich. You might need a couple of weeks to wade through it, becoming familiar with its nuances as you go, but for most people, Java is much more easily learned than other programming languages.

JavaScript and HTML

You embed JavaScript commands inside HTML documents (see Chapter 53, "HTML Programming Basics," for more details on HTML) by enclosing them in the HTML tags <SCRIPT> and </SCRIPT>. The general syntax for a JavaScript program inside an HTML document looks like this:

<SCRIPT language="JavaScript">



    JavaScript statements



</SCRIPT>



The language option inside the <SCRIPT> tag is optional, but it is a good idea to use it to make sure that the browser knows what is incoming. If you want to load the JavaScript from a URL, you need to embed the URL in the <SCRIPT> tag like this:

<SCRIPT language="JavaScript" src="http://www.where.com">



If the JavaScript source is embedded in the HTML file, you can leave off the SRC component. For example, here's a simple JavaScript applet in some HTML code (which has been trimmed down to the essentials):

<HTML>



<HEAD>



...



<SCRIPT language="JavaScript">



   alert("Welcome to my Web site!");



</SCRIPT>



</HEAD>



</HTML>



The alert() function in JavaScript displays the message in a window with an exclamation mark icon next to it. This is usually used to catch your attention when you try to do something critical or illegal, or something that might cause problems. JavaScript's functions, as you can see, are much like those in C. You can define a complete function within a JavaScript file, similar to in a C program.

If you are calling a file with the JavaScript source in it from your HTML code, the convention is to name the file with the .js filetype at the end (sample.js, for example). This is because several applications, including MIME, already recognize the .js filetype and can handle them properly.

We don't have the space here to go into details about JavaScript programming, but many good books have been published on the subject, including Web Programming with Java and Teach Yourself Java in 14 Days (both Sams.net, 1995).

Summary

We've taken a quick look at Java and JavaScript, both of which are available for Linux platforms in both server and client versions. Programming both Java and JavaScript requires a bit of past programming experience, but if you've programmed before, you can use them both to add a lot of features to Web pages and HTML documents. Give them a try! After all, the software is free.