by Frank D. Greco

Introduction to Java (in plain English)

news
Mar 1, 199616 mins

A look at what Java promises -- and delivers

Whatโ€™s more powerful than a double espresso? Faster than a speeding Jamaican Blue Mountain special? Able to leap latte grandes in a single bound?

Itโ€™s Java from Sun Microsystems. Coming from a different Sun, the way cool Java programming language is muscling its way onto the Internet with powers beyond those of mortal computer languages. Flying on the vapor trails of the booming World Wide Web (WWW) service across the ubiquitous Internet, Java is not just a mild-mannered computer programming language working in a metropolitan area network. The technology represented by Java holds the promise of a totally new way of providing products and services to consumers and promises truth, justice and an effective way of programming the information superhighway.

The frenzy

Few would argue with Javaโ€™s reputation as a useful and promising technology. But why is it white hot? (After all, there are lots of useful-and-promising-technologies around.) The answer: Timing. The success of any innovation depends just as much on its market and political, socio-economic timing as on its creativity and utility. Some call it serendipity; some call it plain luck. For example, Elvis and the Beatles had obvious talent, but the enormity of their popularity resulted from surfing a few key waves. Elvis rescued the United States from its postwar doldrums and the Fab Four took us out of the malaise and constraints of the 1950s. Java performs a similar favor by liberating the software community from the battles of the late 1980s and the tedium of the early 1990s.

The immense popularity of Java is a confluence of many circumstances, such as developers sick of the complexity and largess of C++; PC programmers tired of dealing with an arcane OLE and goofy Hungarian notation; window mavens ho-humming Motif and X Window; corporate IT architects complaining of the awkwardness of writing multi-platform software; programmers weary of developing distributed applications with RPC and XDR; users and advertisers worrying about the lack of interactivity and security with the Web; hardware vendors drooling over the idea of ubiquitous computing devices; and probably not least of all, the growing anti-Microsoft sentiment (after all, itโ€™s human nature to root for the little guy, and thereโ€™s nothing little about Microsoft).

Hypermedia + interactivity = hyperactivity

Imagine that there is a system that allows one to interact with all sorts of applications on the Internet. And not only does this system allow you to write programs that run over the Internet, it also provides a high degree of security to programs and users, protects programmers from their own mistakes and offers neat multimedia functionality to display images, play audio and video clips. But wait, thereโ€™s more! This ideal technology also runs on many different types of machines like PCs, Macintoshes and powerful Sun workstations โ€” without any additional programming wizardry. Heck, it even will run on machines that havenโ€™t been invented yet!

This is what Java technology promises, but does it deliver the goods?

Java is a general-purpose, object-oriented computer programming language that offers special features that allow programs to take advantage of the power and flexibility of the Internet.

Apps and AppNots

There are four different types of programs you can write using Java: applications, applets, content handlers, and protocol handlers.

Java applications are standalone programs that require the assistance of the Java interpreter to run. The HotJava Web browser is an example of a Java application. On a Solaris machine, the โ€œHotJavaโ€ program is actually a shell script wrapper that invokes the Java interpreter (Java) with the โ€œcompiledโ€ HotJava application code (i.e., its class file) as an argument. Java applications are analogous to C/C++ applications; they run independently of any Web browser.

Java applets are small applications that are embedded on Web pages. Applets are more security-conscious than Java applications; there are many restrictions on the behavior of applets. For example, unlike applications, applets cannot dynamically link in older C or C++ code. A Java applet requires a browser (or another Java application) to run. Java applets are given a piece of screen real estate in which to draw and a thread of execution, and require the use of another Java program (such as a browser) to actually run.

The remaining two types of Java programs, content and protocol handlers, are special-purpose Java programs that allow Web browsers to dynamically understand new data types such as QuickTime movies, voice recognition or PhotoCD data and new protocols like MIDI or a proprietary stock trading protocol. These types of Java programs make it possible for Java-compliant web browsers to dynamically handle new types of data on the fly. Got a cool site thatโ€™s offering music in MIDI format, but your browser doesnโ€™t know how to handle it? No problem if you have Java. The MIDI handler would be downloaded to your browser along with the data for the handler. Handlers are similar in philosophy to โ€œhelper appsโ€ in Netscape, except they are infinitely more secure.

While not as popular as Java applications and applets, handlers are critical components for internet appliances. They would allow new and safe behavior to be added dynamically to a consumer product that would be a maintenance and security nightmare if implemented in a more rigid technology.

The officially sanctioned buzzword feature list

(from the home office in Mountain View)

  • Simple. Java is a simple and elegant language whose syntax is reminiscent of the enfant terrible of modern computer science, the C++ programming language, except that some of the rarely used, esoteric or redundant โ€œfeaturesโ€ of C++ were eliminated (pause here for wild audience applause). One could describe the Java/C++ comparison as addition by subtraction; James Gosling likes to describe Java as โ€œC++ without the guns, knives or clubs.โ€ It was made simpler primarily to give programmers fewer ways of making mistakes. Once the back-end Java compiler is available, I would expect Java to completely dethrone C++ as the ruling programming language of choice. Long live Java, the wicked witch is dead.

  • Object-Oriented. Unlike C++, Java requires that everything be an object (modulo the primitive types like int, double, etc.). Global data and standalone functions are not allowed, again unlike C++. Every class in Java is directly or indirectly descendent from the grandfather of all classes in Java, the Object class. For those new to object-oriented programming, this means that Object is the root of the inheritance hierarchy; every object possesses at least the same methods (member functions to the C++ crowd) described by Object. In Java parlance, every class โ€œextendsโ€ directly or indirectly from the Object class.

  • Distributed. From its inception, Java was designed to be run over a network. It has inherent extensive TCP/IP and HTTP capabilities. But note that even though Java is typically used on the Web, Java can be used as a replacement for C++ in corporate development shops given a bit more maturity and the availability of the back-end (โ€œjust-in-timeโ€) compiler. SunSoft has also announced that they will soon bring CORBA-style Interface Definition Language bindings to Java, so that Java programs will be able to invoke remote procedures in server-based objects over a net.

  • Interpreted. Similar to other conventional programming languages, Java programs are written by knowledgeable programmers using the Java source language (and saved in files with a .java extension) and translated to a format that allows it to run on your computer hardware. Unlike other conventional language translators, however, the ever-stringent Java โ€œcompilerโ€ converts Java source code into a machine-independent format that allows it to run on any computer hardware that has the Java runtime system (the โ€œJava Virtual Machineโ€). These Java โ€œbytecodes,โ€ named because the majority of the binary opcodes are one byte in length for efficiency, are really the key to application portability in the Java environment. This notion of an abstract machine is heavily borrowed from Kenneth Bowlesโ€™ innovative P-System used in UCSD Pascal (circa early 1980s).

    Since the Java runtime system is actually independent from the Java source language that a programmer would create, other languages and other tools could potentially generate the machine-independent Java bytecodes. Thereโ€™s nothing to stop someone from creating a version of BASIC that generates Java bytecodes; and it would be 100 percent compatible with bytecodes generated by the standard Java translator. Thereโ€™s also no reason why a visual development environment complete with drag-and-drop, point-and-click, cash-and-carry features could not directly generate Java bytecodes.

  • Robust. One of the best and worst features of languages like C and C++ is the abstraction of a pointer โ€” that is, a machine address. Pointers and pointer manipulation can be used by knowledgeable programmers to tremendous advantage in these legacy languages; however, many times they are the cause of hard-to-find runtime errors. Does the term memory leak strike fear in your hearts, fellow code warriors? Pure Software, a publicly traded company, exists solely because pointers (and careless programmers) cause memory leaks or unexplained runtime โ€œbogosities.โ€ Java eliminates pointer manipulation completely from the language, and in doing so eliminates a large source of runtime errors. In addition, developers donโ€™t even have to remember to deallocate memory in Java; there is a (decidedly non-optimal) garbage collection mechanism that does the trick.

  • Secure. Java is a client-side technology. After the translation to Java bytecode phase, Java programs are, in effect, downloaded from the host machine using conventional Web server technology (i.e., using HTTP) and then run on your client machine. Since weโ€™re now downloading Java programs located all over the world to our own machine, some precautions are taken to attempt to prevent computer viruses from being spread to your machine. The Java runtime system (on your computer) doesnโ€™t assume anything; it looks at the incoming Java bytecodes and verifies that the program code is safe. If it isnโ€™t safe, the runtime system rejects the code and refuses to run it, sort of like a code bouncer. Once the strict verification process has been passed, the little application (applet) proceeds to run.

    Presuming Java is totally safe and completely secure might be a tad too risky. There are only three things that are certain in life: death, taxes and Shark Week on the Discovery Channel; beyond these, nothing is guaranteed. But Java is certainly dramatically more secure than most current distributed programming technologies, given its youth, and certainly vastly more secure than C or C++. Clearly there are some security problems to fix and yet-discovered holes to plug. Based on discussions in the comp.lang.java and comp.security Usenet newsgroups, there are some interesting (and several uninteresting) ways to circumvent Java security. As Java and the Internet mature, security will certainly improve.

  • Architecture-neutral and portable. The Java bytecodes are independent of any underlying architecture. Byte endian issues are, for the most part, negligible. Character sets are Unicode-based for internationally portable applications. If you use certain file I/O classes, you can render your data portable as your Java code. For example, the DataInputStream and DataOutputStream classes utilize eXternal data representation to normalize your data to a network canonical format (in other words, your data can be used by many different types of processors and machines). The portable Java runtime system is or soon will be available (currently in non-production states) on a variety of systems, including Solaris, Windows 95 and Windows NT, SunOS 4.1.3, AIX, HP/UX, OS/2, and Digital Unix (OSF/1).

  • High Performance. Currently, Javaโ€™s runtime environment is interpretive, and as techies, we know that interpreters exact a performance toll. Performance figures discussed in the Java newsgroup seem to range from 20-30 times slower for CPU-intensive programs to 5 times slower for some network-based programs. Sun promises performance rivaling native C/C++ speed once the interpreter in the runtime environment is converted to a just-in-time class compiler. But despite an anticipated performance degradation, Java can be made to perform some surprisingly powerful stunts. Check out http://www.geom.umn.edu/~daeron/apps/CV/viewer.html and http://reality.sgi.com/grafica/java3d to see how much performance these clever programmers have squeezed out of a beta version of an interpreted language. (Care to bet on Java performance futures?)

  • Multithreaded. The notion of multithreading is basically the ability to run several tasks within the context of one large application. For most applications, multithreading improves interactive performance. Not only does Java give programmers the ability create threads, Java itself is inherently multithreaded. The garbage collection subsystem, for example, runs as a low-priority thread. Since multithreaded applications typically share data (all threads of an application live in the same data space), they often were difficult to build reliably. It was necessary to mediate concurrent access to thread data a la shared memory in System V Unix or Windows NT using awkward semaphore or mutex constructs. To make it easy for programmers to use threads, Java borrows a concept from Xeroxโ€™s Cedar environment and seminal Mesa programming language and offers the synchronized keyword. Code wrapped with the synchronized keyword can be accessed by only one object at a time.

  • Dynamic. Experienced software developers understand that software (and software requirements) evolve; they are rarely cast in stone. The microsecond an executable is released to your user community, thereโ€™s either a bug discovered or an RFE (request for enhancement) submission. Fixing and distributing a patch or new functionality can be awkward or just plain painful with C++; a quick read of your palmtop shows that thereโ€™s a huge recompile in your future. Java allays this problem by deferring much linkage manipulation until runtime. This feature practically eliminates the so-called fragile superclass problem in C++, where a change in a parent class forces a recompile of the child classes. Applications can be โ€œpatchedโ€ dynamically. Besides the obvious cross-platform benefits, the ease of application distribution with Java is a huge win for the corporate intranets of the world.

    And unlike C++, Java has no name-mangling linker problems. This benefit alone will improve the corporate bottom line as corporate dental plans no longer have to cover teeth gnashing.

Source sport

Whatโ€™s a techie article without some source code to mistype (maybe you should cut and paste it โ€” after all, this is a Web-based magazine), fix, compile, fix, compile, run, fix, compile, run and then lie that it compiled on the first shot? The first thing is to obtain the Java Developer Kit (JDK) from Sun. You can download the JDK from http://www.java.sun.com/JDK-1.0/index.html and install it on your PC (Windows 95 or NT) or beefy Sun workstation running Solaris 2.3+. The JDK includes a Java interpreter, the Java bytecode compiler, a Java applet viewer, a Java debugger and a host of other Javanian utilities.

Letโ€™s look at a simple Java applet and a simple Java application. But before we attempt to compile and run our Java programs, a few environment variables should be set:

C shell
setenv PATH /home/java/bin:$PATH
setenv CLASSPATH /home/java:.
Windows NT
PATH=C:windowscommand;c:javabin;c:dos
set CLASSPATH=C:java;.

Can you say โ€œHello World?โ€

Hereโ€™s a simple Hello World Java applet. It simply displays the string โ€œHello Worldโ€ within the bounding rectangle of an applet. This program, helloworld.java, will also play an audio file if youโ€™ve recorded your own โ€œHello Worldโ€; remove the // comment construct before compiling:

import java.applet.*;
import java.awt.Graphics;
public class helloworld extends Applet {
    public void paint (Graphics g){
        g.drawString("Hello World", 25, 25);
//      play(getDocumentBase(), "helloworld.au");
    }
}

Now compile this Java applet with the Java bytecode compiler:

C:SRC>javac helloworld.java

Now create a little HTML file that uses this Java applet:

C:SRC>type helloworld.html
<html>
<applet code=helloworld.class
    width=200
    height=200>
</applet>
</html>

Finally, fire up the applet viewer utility:

C:SRC>appletviewer helloworld.html

or use Netscape 2.0b6a or better to read this HTML page:

Location: file:///c:/src/helloworld.html

As you can see, the mechanics of writing Java applets are very easy. Detailed information on applets can be found in the book Hooked On Java by Arthur Van Hoff and Sami Shaio, and of course at the Sunโ€™s Java home page. Writing Java applications is just as simple.

Hereโ€™s hellofrank.java, a Java application that displays a string to the standard output device.

class HelloFrank {
    public static void main (String args[]){
        System.out.println("Howdy Frank");
    }
}

Now compile this Java application with the Java bytecode compiler:

C:SRC>javac hellofrank.java

But now instead of using this Java program on an Web page described by an HTML file, we run the application by invoking the Java interpreter directly on the Java class file. Be aware that the name of the file that contains the bytecode version of your Java file is derived from what you named the class including any case-sensitive differences.

C:SRC>java HelloFrank
    Howdy Frank

For additional details on Java applications, visit Java Central at http://java.sun.com.

Hyper-jumping on the bandwagon

While the Java language will certainly be popular with experienced programmers, most users of this wonderful technology clearly will be using Java indirectly through higher-level tools. This fact has been historically true for other many other programming languages. Several well-known companies (such as Netscape, Sun, SGI, Macromedia, Symantec, Metrowerks, Natural Intelligence, and Borland) are currently building applications and programmer toolkits for Java. However, as radically innovative technologies typically evolve, I would expect a brand new startup company will rise above the expected IDE vendors to take the helm of the Java developer ship.

In the late โ€™70s and early โ€™80s, there were all sorts of interesting little software companies started in garages all over the world. It truly was an exciting time for software developers. But then during the mid-80s and the early โ€™90s, those garages became extinct; it was virtually impossible for the little developer to create the next killer application. Massive amounts of money were needed for shelf-space. Without the all important distribution channel, your killer app is a killed app. Well, the garages are now back; the Internet is your distribution mechanism and the killer apps are being written in Java.

Frank D. Greco is the president and CEO of Crossroads Technologies Inc., providing consulting and systems integration in advanced technologies such as Java and the Internet. He also taught a developer track session at the very first Java Day last September in New York. This article (originally titled โ€œWaiter! What is this Java doing in my soup?โ€) is copyright 1996 by Frank D. Greco, Crossroads Technologies Inc. You may copy any or all parts of this article provided that this copyright paragraph is included.