Java has been in existence for several years, but it has been getting a great deal of press recently (including new books, magazines, and conferences dedicated to Java applications).
Why? Could it have anything to do with the Internet?
Java(TM) is a new language from Sun Microsystems
Java is related to many programming languages: C, Simula, Modula, Pascal, C++, etc.
It is intended to be very portable - or, at least, it should be possible to build Java execution environments for a wide variety of computers and operating systems.
Sun Microsystems hopes that Java will open up a new world of network computing environments, which will permit locally-executable programs to exist on many servers on a computer network.
But this environment is very limited:
Java helps to overcome some of these limitations. We can compile Java programs into a form that can be downloaded over the Internet and executed "locally".
Most Web-based interactive forms are designed to have their computation done on the "server" machine. This is fine if the application is searching a database on the server, but it isn't so efficient if it performing a bunch of computations that affect the local display.
Sun Microsystems experimented with a new Web browser (called HotJava) which could interpret downloaded Java programs
Now the Netscape Navigator 2.0 product also contains a Java interpreter
The HotJava browser currently available from Sun is old. The definition of Java has changed over the last six months, so it won't execute the new-style Java applets. Netscape 2.0 is up-to-date, though, so it can execute new Java applets. Sun plans to come out with a new edition of HotJava soon.
The syntax of Java is quite similar to C and C++
There are a few interesting differences
In C and C++, it is possible to define structures and arrays that are stored in static memory or on the stack. But in Java, all class objects and arrays are stored in dynamic memory (also known as the "heap"). In Java execution environments, dynamic memory is managed by a garbage collector (just like in Lisp, Simula, and Eiffel), so no programmer intervention is necessary to explicitly free up objects. Therefore, memory management is easier for Java class developers than it is for C++ class developers, but Java's memory scheme is much less efficient.
Some other features of C and C++ that Java programmers might miss:
Here is a very simple example program in Java:
/* file HelloApp.java */ public class HelloApp { public static void main(String args[]) { System.out.println("hello world"); } }
A Java application must be a class, and that class must contain a main() static member function. The standard library function println() is a lot like the writeln function in Pascal.
You can compile the program this way: javac HelloApp.java
You can run it by calling the Java interpreter: java HelloApp
The Java compiler (the javac HelloApp.java command) will parse the HelloApp.java file, find standard library function references in the library file, and finally create a Java bytecode file HelloApp.class.
The java HelloApp command will open and read the Java bytecodes in the HelloApp.class file (and it will also open and read other files that contain other class functions that the application calls). In this example, the Java interpreter will write the hello world message on the screen.
/* file CheckFileApp.java */ import java.io.File; public class CheckFileApp { public static void main(String args[]) { int i; for (i = 0; i < args.length; i++) { File f; f = new File(args[i]); if (!f.exists()) { System.out.println("file " + args[i] + " doesn't exist"); } } } }
The import statement is needed, because this application uses the library class File. The import statement is required for all external classes not part of the java.lang package.
This program will print out a line like this:
file xxx doesn't exist
for every filename on the command line that doesn't exist. In this program, the declaration
File f;
creates a local reference to a File object, but no File objects are actually created until the statement
f = new File(args[i]);
is reached.
The File objects don't have to be deleted, because the garbage collector will eventually recover all the space that was used for File objects.
/* file TailApp.java */ import java.io.*; public class TailApp { // show last 5 lines of a file public static void main(String args[]) { last_five_lines(args[0]); } static void last_five_lines(String fname) { DataInputStream stream = new DataInputStream(new FileInputStream(fname)); int i = 0, max = 5, j = 0; String tmp; String strs[] = new String[max]; while ((tmp = stream.readLine()) != null) { strs[i++] = tmp; if (i == max) i = 0; } for (j = i; j < max; j++) System.out.println(strs[j]); for (j = 0; j < i; j++) System.out.println(strs[j]); } }
This example program shows the use of an array of Strings. (String is a built-in datatype in Java.) The array will keep track of the last five lines read in from the file - all of the previously read lines are in String objects that aren't referred to by any active object (so they might be reclaimed by the garbage collector).
This application is not quite correct, because it has to be able to handle the situation where the file doesn't exist. This can be done using a "try block" and exceptions:
static void last_five_lines(String fname) { try { ...main body of the function... } catch (FileNotFoundException e) { System.out.println("Can't open file " + fname); } catch (IOException e) { System.out.println("IO error in file " + fname); } }
Web browsers are set up to run "applets" - little applications that execute within a Web page.
/* file HelloApplet.java */ import java.awt.*; public class HelloApplet extends java.applet.Applet { Font f = new Font("TimesRoman", Font.BOLD, 36); public void paint(Graphics g) { g.setFont(f); g.setColor(Color.red); g.drawString("Hello!", 5, 35); // upper left corner of the text will be 5 pixels // from the left edge and 35 pixels from the top } }
The function paint() is defined in the Applet class, but we are redefining it in the HelloApplet class.
Applets are often more complicated than applications, but they are easier to write because the basic Applet class does a lot of the work.
There are five important functions in the Applet class that can be redefined:
Here is how to add an applet into your Web page with the <APPLET> tag:
<HTML> <HEAD> <TITLE>My Java Page</TITLE> </HEAD> <BODY> Here is my example Java applet: <BR> <APPLET CODE="HelloApplet.class" WIDTH=300 HEIGHT=100> </APPLET> </BODY> </HTML>
The Web browser should try to download the program found in the HelloApplet.class file and execute it - displaying its graphics in a subwindow of 100x300 pixels.
The simple applet that we created will simply display some text in its piece of the screen, but it can do a lot more.
The standard Java class libraries include some classes to help write interactive applets.
The collection of graphics classes is called the Abstract Windowing Toolkit (or AWT)
Many of the widgets that are created by AWT will take advantage of the local windowing system: Motif, Windows NT, etc.
AWT tries to be the "least common denominator", so it can't do things that are real fancy.
Java's graphical libraries can currently display GIF and JPEG files.
The typical Panel class in Java will look like this:
public class ButtonPanel extends Panel { public ButtonPanel() { add(new Button("OK")); add(new Button("Cancel")); add(new Button("Quit")); } public boolean action(Event evt, Object arg) { if (evt.target instanceof Button) { String buttonstr = (String) arg; if (buttonstr.equals("OK")) do_okfunc(); if (buttonstr.equals("Cancel")) do_cancelfunc(); if (buttonstr.equals("Quit")) System.exit(1); } return true; } .... }
The add() calls assemble the Panel container. The action() function is needed to handle the user input events.
A typical Java application may have several panels that are added into an Applet object. Each Panel can have its own action() function.
An interface in Java is like an abstract base class in C++. It is a declaration of a set of functions without definitions.
/* file XYZInterface.java */ public interface XYZInterface { public abstract int blorf(); }
It can be used in situations where C++ would use multiple inheritance:
/* file MyApplet.java */ public class MyApplet extends java.applet.Applet implements XYZInterface { // the class developer must define the function blorf()... }
Java doesn't implement multiple inheritance, but the most common use of multiple inheritance is to define "mix-ins" (a mix-in is a base class that only contains declarations of functions that any derived class must implement), and Java's interface feature implements mix-ins without allowing some of the trickier things that can be done with a more general multiple inheritance feature.
Java permits a bunch of classes and interfaces to be grouped together into a package. A package declaration at the beginning of a Java source file affects the "official name" of the public class in that file:
/* file MyUtilClass1.java */ package COM.lucent.myProject.Utility; public class MyUtilClass1 { .... } /* file MyUtilClass2.java */ package COM.lucent.myProject.Utility; public class MyUtilClass2 { .... } /* file MyApp.java */ import COM.lucent.myProject.Utility.MyUtilClass1; import COM.lucent.myProject.Utility.MyUtilClass2; public class MyApp { private MyUtilClass1 u1; .... }
The package statement must be the first statement in the file. It causes the compiler to prepend the package name to the "official name" of each class defined in the file.
The import statement allows the application writer to leave off the package name (COM.lucent.myProject.Utility) from the imported class name for the rest of this source file.
You can import all of the classes from a given package like this:
import COM.lucent.myProject.Utility.*;
Each Java source file (ending in ".java") will generate one or more "class" files. The Java runtime system will load and interpret all of the needed classes for a particular application:
There are several performance drawbacks to form-based interaction using HTML:
Security issues are also a concern:
On the other hand, Java applets provide a better interactive environment:
If you are performing a series of Forms operations within a single HTML page, you will probably have to retransmit some information multiple times, because each server-side operation is processed in a separate process.
Most gateway programs are written in interpreted languages such as shell or perl. The author of these gateway programs needs to be diligent: all user input should be checked carefully. It is a good idea to use a "restricted" shell or a special version of perl to prevent inadvertent or malicious changes to files on the server machine.
Java applets can use the computational facilities of the client rather than taxing the server. In addition, Java's security features make it harder for bogus user input to harm files on both the client and server.
Since Java is "semi-interpreted" from a machine-independent intermediate code, it isn't the fastest environment in the world.
It is possible to call C functions from Java code.
There is a Java to C translator (java2c) which can create much faster native code from existing Java libraries.
The following table gives the amount of time to do 10 million operations on an Intel 486DX2/50:
operation native Java ----------------------------------------------------- integer addition 2.8 sec 90 sec integer multiplication 5.2 95 integer division 12.0 100 floating point addition 7.4 95 floating point multiplication 17.3 107 floating point division 17.9 108
The Java Development Kit (JDK) is available (free!) from Sun's Java Web site. Check the URL http://java.sun.com
Several of the popular books on Java include a CD-ROM containing the JDK and some example applications and applets.
Sun will soon release their "Java Workshop," which is a graphical development environment for Java.
Some compiler vendors and development environment builders (Symantec, Borland, TakeFive Software) are producing Windows-based development environments.
Some of the CD-ROMs in the current books contain Beta versions of the JDK, so you might still have to download the JDK software from Sun to get the latest version. JDK is available by anonymous FTP from several mirror sites:
ftp.javasoft.com ftp.science.wayne.edu, /pub/java directory sunsite.unc.edu, /pub/languages/java directory www.blackdown.org, /pub/Java directory java.dnx.com
A good source of current interesting Java applications on Internet is:
and there is a major "Frequently Asked Questions" list at:
Doug Lea has written a good tutorial on patterns, Java, and concurrency:
http://g.oswego.edu/dl/pats/aopintro.html
Laura Lemay and Charles L. Perkins, Teach Yourself Java in 21 Days, Sams.net Publishing, 1996, ISBN 1-57521-030-4.
Arthur van Hoff, Sami Shaio, and Orca Starbuck, Hooked on Java, Addison-Wesley, 1996, ISBN 0-201-48837-X.
James Gosling and Henry McGilton, "The Java Language Environment," Sun Microsystems White Paper, October 1995.
Peter van der Linden, Just Java, Prentice-Hall, 1996, ISBN 0-13-565839-X.
David Flanagan, Java in a Nutshell, O'Reilly & Associates, 1996, ISBN 1-56592-183-6.
There are several books from the Java group at Sun Microsystems that will be out this summer.
There is also a magazine Java Report, published bimonthly by SIGS Publications.