About the Book Java Tutorial Java Links
Java FAQ Newsletter

JAVA DEVELOPER'S RESOURCE

Java FAQ list and Tutorial: a work in progress

This is the Java FAQ list. A Java Tutorial is being developed as simultaneously as time permits. If you already know C++, this FAQ list is probably the most useful. If you don't know C++ or C, you may want to go through the tutorial before delving into the later sections of this FAQ.

If you're reading the text version via Usenet, I do apologize that parts of it may be less intelligible than possible in HTML. Please refer to the HTML version at http://sunsite.unc.edu/javafaq/javafaq.html.

This document is Copyright 1995, 1996 by Elliotte Rusty Harold. For information about reproduction, redistribution and other such rights please see the end of this file.

Table of Contents

What is Java?

Java, formerly known as oak, is an object-oriented programming language developed by Sun. It shares many superficial similarities with C, C++, and Objective C (for instance for loops have the same syntax in all four languages); but it is not based on any of those languages, nor have efforts been made to make it compatible with them.

Java is sometimes referred to as C++ ++ --. The language was originally created because C++ proved inadequate for certain tasks. Since the designers were not burdened with compatibility with existing languages, they were able to learn from the experience and mistakes of previous object-oriented languages. They added a few things C++ doesn't have like garbage collection and multithreading; and they threw away C++ features that had proven to be better in theory than in practice like multiple inheritance and operator overloading. (There's still argument over whether they made the right choices. I tend to think they were correct to throw out operator overloading and probably correct to throw out multiple inheritance. For now let's just say that neither choice is likely to be reviewed soon.)

Even more importantly Java was designed from the ground up to allow for secure execution of code across a network, even when the source of that code was untrusted and possibly malicious. This required the elimination of more features of C and C++. Most notably there are no pointers in Java. Java programs cannot (at least in theory) access arbitrary addresses in memory.

Furthermore Java was designed not only to be cross-platform in source form like C, but also in compiled binary form. Since this is frankly impossible across processor architectures, Java is compiled to an intermediate byte-code which is interpreted on the fly by the Java interpreter. Thus to port Java programs to a new platform all that is needed is a port of the interpreter.

Finally Java was designed to make it a lot easier to write bugfree code. Shipping C code has, on average, one bug per 55 lines of code. About half of these bugs are related to memory allocation and deallocation. Thus Java has a number of features to make bugs less common:

Where did Java come from?

In the late 1970's Bill Joy thought about doing a language that would merge the best features of MESA and C. However other projects (like cofounding Sun) intervened. In the late 1980's he got Sun's engineers started on a complete revision of the UNIX operating system that involved merging SunOS4.x with AT&T's SYSVR4.

In 1989 Joy sold his Sun stock, invested heavily in Microsoft and moved out of mainstream Sun to Aspen, Colorado. By the early 90's Bill was getting tired of huge programs. He decided that he wanted to be able to write a 10,000 line program that made a difference. In late 1990 Bill wrote a paper called Further which outlined his pitch to Sun engineers that they should produce an object environment based on C++. Today Joy freely admits that C++ was too complicated and wasn't up to the job.

Around this time James Gosling (of emacs fame) had been working for several months on an SGML editor called "Imagination" using C++. The Oak language (now Java) grew out of Gosling's frustration with C++ on his "Imagination" project.

Patrick Naughton, then of Sun, now vice-president of technology at StarWave, started the Green Project on December 5th, 1990. Naughton defined the project as an effort to "do fewer things better". That December he recruited Gosling and Mike Sheridan to help start the project. Joy showed them his Further paper, and work began on graphics and user interface issues for several months in C.

In April of 1991 the Green Project (Naughton, Gosling and Sheridan) settled on smart consumer electronics as the delivery platform, and Gosling started working in earnest on Oak. Gosling wrote the original compiler in C; and Naughton, Gosling and Sheridan wrote the runtime-interpreter, also in C. (The Green project never wrote a single line of C++.) Oak was running its first programs in August of 1991. Joy got his first demos of the system that winter, when Gosling and Naugton went skiing at Joy's place in Aspen.

By the fall of 1992 "*7", a cross between a PDA and a remote control, was ready In October of 1992 this was demoed to Scott McNealy, Sun's president, who was blown away. Following that the Green Project was set up as First Person Inc., a wholly owned Sun subsidiary.

In early 1993 the Green team heard about a Time-Warner request for proposal for a settop box operating system. First Person quickly shifted focus from smart consumer electronics (which was proving to be more hype than reality) to the set-top box OS market, and placed a bid with Time-Warner.

Fortuitously, Sun lost the bid. The Time-Warner project went nowhere, the same place it probably would have gone if Sun had won the bid. First Person continued work on settop boxes until early 1994, when it concluded that like smart consumer electronics settop boxes were more hype than reality.

Without a market to be seen First Person was rolled back into Sun in 1994. However around this time it was realized that the requirements for smart consumer electronics and settop box software (small, platform independent secure reliable code) were the same requirements for the nascent web.

For a third time the project was redirected, this time at the web. A prototype browser called WebRunner was written by Patrick Naughton in one weekend of inspired hacking. After additional work by Naughton and Jonathan Payne this browser became HotJava. The rest, as they say, is history.

Information in this section is primarily based on the first hand accounts of Bill Joy and Patrick Naughton (which don't always agree). No doubt other people have still different memories of what occurred. If you've got any more first hand information about what went on in the Green project I'd like to hear from you.

Doesn't the World Wide Web have something to do with this?

Not necessarily. Java is a programming language. When work began on what has become Java, the World Wide Web was just getting started at CERN and Mosaic wasn't even a glint in Marc Andreesen's eye. The original use of the Java language (settop boxes) required security and the ability to execute code from untrusted hosts. It turns out these are virtually the same requirements for allowing people to download and run programs from the Web. No other language has the built-in security of Java. The key here are the security features. The object-oriented nature of Java is secondary, and mainly reflects the preferences and prejudices of the developers who set out to write a secure language. The C-like syntax of the language is even less important to the problem.

At the lowest level the advantage of Java to the web is that it provides a secure, cross-platform way for code to be executed. At a somewhat higher level Java adds several features to existing web sites:

Arbitrary Graphics
Java lets the server draw pictures in a window on the client. In theory this allows a web page to do anything a regular program can do by drawing in a window.

Arbitrary Data Types
In practice rather than using graphics primitives to create your desired web page you'd use a graphics program to draw the page and then write a program that could read and display the file formats of that program. Java lets you write content-handlers that display any particular data format. This way you can download your data and your data display program rather than downloading a bitmapped snapshot of the display. People are already using this to add sound and animation to web pages. Rather than having to download a file and spawn an external viewer, the viewer is included with the data; and the data is displayed right on the page.

Less Load On The Server
CPU intensive cgi-bin scripts place a large load on a server, particularly at busy sites. With Java you can offload the calculations to the client's PC. I've written an applet that calculates all possible ram configurations for a given Mac model. However on models with many memory slots the sheer number of permutations can tie up even a fast machine for several hours. Publishing this as a cgi-bin would bring my server to its knees, but by publishing it as a Java applet I can distribute the load across all the machines that want to run it.

More User Interaction
Finally Java allows for more interaction with the user. Java not only allows you to paint arbitrary data on the screen. It also allows you to collect input from the user in the form of mouse clicks, keystrokes and the like. This lets you put almost any application on your web page that doesn't require disk access.

What Platforms does Java run on?

Sun has made a Java development kit available for Sparc and X86 Solaris, Windows NT for Intel, Windows 95, MacOS 7.5 on PowerMacs and 68020, 68030 and 68040 Macs.

An IRIX port has mostly been completed by Simon Leinen. SGI's own port is available at http://www.sgi.com/Products/cosmo/cosmo_instructions.html

A Linux port has been mostly completed. See http://java.blackdown.org/java-linux.html.

IBM has ported Java to OS/2 and AIX. See http://ncc.hursley.ibm.com/javainfo/ . IBM is also rumored to be porting Java to Windows 3.1. However for various reasons such a port is extremely difficult.

The OSF is porting Java to Unixware, HP/UX, Sony NEWS and Digital Unix. The alpha 3 HP/UX (9.0 and 10.0) and Unixware 2.0 ports are available. See http://www.osf.org/mall/web/javaport.htm.

Other ports are underway for Nextstep, SunOS 4.1, the Amiga and possibly other platforms.

In the past new versions of Java have most often been made available first for Solaris. If you have to have the latest version as soon as it's released, or if you're developing "Bet your company" applications with Java, you should probably be running Solaris on a SparcStation. Otherwise, if you just want to learn the language, you can get away with an Intel based Windows 95 or NT machine with a lot of RAM.

Netscape 2.0 and later will play Java applets on Windows NT, Windows 95, Solaris, SunOS 4.1, Linux and most other Unix platforms. A beta version of Netscape 2.0 for the Mac also supports Java.

Do I need to know C++ to learn Java?

No. Java is in fact a much easier language to learn than C++.

A little further out in left field, it isn't even necessary to know Java to write Java programs. Intermetrics is beta testiing an ADA-95 to Java byte code compiler. Other such cross-compilers are probably possible including ANSI Fortran-77. However the one most people probably want, that is a C/C++ to Java byte code compiler, is probably not possible due to the severe limitations Java places on pointers.

What other Java Resources are available?

Web Sites

The key site for Java information is http://www.javasoft.com/. This is Sun's official site for Java, and contains the latest published version of all official Java information.

This site has grown quite busy and is mirrored in several other places including

USA
UK
http://sunsite.doc.ic.ac.uk/packages/java-http/
Sweden
http://www.cdt.luth.se/java/
Germany
http://sunsite.informatik.rwth-aachen.de/Mirror/java/
Japan
http://www.glocom.ac.jp/mirror/www.javasoft.com
Singapore
http://sunsite.nus.sg/hotjava/
Korea
http://cair-archive.kaist.ac.kr/java/
China
http://www.math.ac.cn/sunsite/
Here are the most important pages at that site:

The Documentation Page
The most important page on this site is the Documentation page at http://www.javasoft.com/java.sun.com/newdocs.html. Most of the other pages are linked off of this page or its children.

The Java Tutorial: Object Oriented Programming for the Internet
The beginnings of a Java tutorial is at http://www.javasoft.com/tutorial.

The complete set of documentation for the JDK 1.0.2 release

The complete set of documentation for the 1.0alpha3 release
This is the same documentation included with HotJava with maybe a few minor corrections. These are mostly obsolete but are occasionally useful when you're trying to understand things that have become undocumented in later releases.

The Java Language Specification
This is to Java as Kernighan and Ritchie is to C. Note, however, that since Java is an object oriented language much of its functionality is tied up in the class library and is not present in the language itself. This version covers the alpha releases. A beta version is available in PostScript format only. Parts of the final 1.0 language spec are also available in PostScript format from http://www.javasoft.com/java.sun.com/newdocs.html

The Java Class API
This is as to Java as P.J. Plaugher is to C, only more so.

Java, The Inside Story
This is the first article about the genesis and history of Java. You may also be interested in Chris Warth's comments about the article.

Java at Yahoo
As usual Yahoo has fairly useful collections of links to Java info.

Java Class Hierarchy Diagrams
Charles L. Perkins has prepared a number of diagrams which show the class hierarchy for Java packages. These are in PostScript format.

The Java Online Bibliography
General, non-technical articles about Java on the Web

The Wild, Wild World of HotJava
Various news about Java and HotJava, mostly non-technical, compiled by Joey Oravec.

Programming Active Objects in Java
Doug Lea's explication of the philosophy of active object design using Java as the implementing language.

Gamelan
A collection of links to useful Java resources. Among other things this has a fairly large compendium of applets.

AWT Tutorial
Nelson Yu's preliminary tutorial about the awt.

From Hello World to Ticker Tape in Seven Steps
Timothy Arnold's applet tutorial.

Cafe Au Lait
As well as being my favorite kind of coffee, Cafe Au Lait at http://sunsite.unc.edu/javafaq/ is the site where I store the HTML version of this Java FAQ list. It also contains a Java tutorial, a list of nascent Java user groups, a Java book list, and more.

Mailing Lists

There are several Java related mailing lists. Complete details are available at http://www.javasoft.com/mail.html.

java-announce
A moderated list with announcements of interest to Java users. If you want to know when the Mac version is released subscribe to this list. Please don't bother asking on the other lists.

hotjava-interest
For discussion of the HotJava browser. This list has very little useful traffic. Almost all posts here are pointless cross-posts from java-interest.

To subscribe to any or all of these lists send the word "subscribe" in the BODY of a mail message to listname-request@www.javasoft.com, where listname is the the mailing list you want to subscribe to.

When you send email to these lists never, never cross-post. If you can't decide where your message properly belongs flip a coin. Please don't send it to every single list.

There is also a mailing list about Java, Kerberos and DCE at java-kerberos@lists.stanford.edu. To subscribe send email to majordomo@lists.stanford.edu with the words "subscribe java-kerberos" in the BODY of your mail message.

Newsgroups

alt.www.hotjava
A newsgroup for the discussion of the HotJava browser.

comp.lang.java
A newsgroup for the discussion of the Java language. This newsgroup is likely to be split in the near future.

Books

As of June, 1996 I recommend two books in particular for those learning the language. The first is Java in a Nutshell: A Desktop Quick Reference for Java Programmers by David Flanagan from O'Reilly & Associates, Inc., ISBN: 1-56592-183-6, $19.95. This is an excellent introduction to Java for C and C++ programmers and an excellent reference for everyone.

The Java Handbook by Patrick Naughton, $27.95, Osborne/Mcgraw-Hill, is a moderately comprehensive introduction to Java.

For details about these and many more books see http://sunsite.unc.edu/javafaq/books.html

Java for C++ programmers

In the large Java looks like Smalltalk. In the small it looks like C. The syntax of Java is deliberately similar to C. If you know C you already know large chunks of Java. Here, in brief, is Java syntax for C programmers:

Data Types

Java's primitive data types are very similar to those of C. Strings, booleans, and true arrays have been added. However the implementation of the data types has been substantially cleaned up in several ways.

  1. Where C and C++ leave a number of issues to be machine and compiler dependent (for instance the size of an int) Java specifies everything.

  2. Java prevents casting between arbitrary variables. Only casts between numeric variables and between sub and superclasses of the same object are allowed.

  3. All numeric variables in Java are signed.

Here are the detailed data types:

boolean
1-bit. May take on the values true and false only.

true and false are defined constants of the language and are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. Booleans may not be cast into any other type of variable nor may any other variable be cast into a boolean.

byte
1 signed byte (two's complement). Covers values from -128 to 127.

short
2 bytes signed (two's complement), -32,768 to 32,767

int
4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type.

long
8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float
4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).

Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g. float to short) the fractional part is truncated and the conversion is done modulo the length of the smaller type.

double
8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).

char
2 unsigned bytes, Unicode.

Chars are not the same as bytes, ints, shorts or Strings.

Strings
Strings are a special object defined in java.lang.String. They are not null terminated and are not the same as an array of chars.

array
Arrays are objects. Multidimensional arrays are created via arrays of arrays.

sizeof isn't necessary in Java because all sizes are precisely defined. i.e. an int is always 4 bytes. This may not seem to be adequate when dealing with objects that aren't base data types. However even if you did know the size of a particular object, you couldn't do anything with it anyway. You cannot convert an arbitrary object into bytes and back again.

Control Statements

Java contains if, else, for, while, do while and switch statements. The syntax is identical to C's. However all condition tests must return boolean values. Since assignment and arithmetic statements do not return a boolean value, some of the more obfuscated condition tests in C are prohibited.

Command Line Arguments

Command line arguments are like C's except that argv has become a string array commonly called args and args[0] is the first command line argument, not the name of the program. The other arguments are all shifted one to the left from where they'd be in C or C++.

Comments

Java supports both the /* This is a comment */ comment from C and the
// This is a C++ comment
comment from C++.

However comments that begin with a /** are treated specially by the compiler. These comments should only be used before a declaration. They indicate that the comment should be included in automatically generated documentation for that declaration.

Classes

Java does not support multiple inheritance.

Superclasses of a class are indicated with the extends keyword rather than with a :.

How is Java unlike C++?

Two classes of language features have been removed from C++ to make it Java. These are those language features which make C++ unsafe and those which make it hard to read.

Features removed that make Java easier to read and understand than C++ include #define, typedef, operator overloading, enum, unions and structs.

The main feature removed to make Java safer and more robust than C++ is pointer arithmetic.

Other features removed include global variables, standalone functions (everything is a method), friend functions (Everything in a package is a friend of everything else in the package.) and non-virtual functions.

A number of features have been added to Java to make it safer including true arrays with bounds checking, garbage collection, concurrency, interfaces (from Objective C) and packages. There is no need to explicitly allocate or free memory in Java.

Methods

Methods must be defined within the block that defines the class they belong to, not outside of it as they commonly are in C++.

Concurrency

Java is internally multithreaded. The model includes threads, synchronization, and monitors.

How Do I...

Make a linked list without pointers?

Short answer: Use the Vector in java.util. It can do anything a linked list can do and a little more and saves you a lot of coding which, after all, is the point of OOP and the class library. However it is array based so insertions or deletions from the middle of a Vector are not as efficient as with a true linked list.

Long answer: Object variables in Java are all references. A reference would be a pointer in any other language. The main difference is that you can't do pointer arithmetic on references. Therefore wherever you'd use a pointer to an object in C++, in Java you should just use the object itself.

On the other hand the primitive data types (int, float, double, char, byte, short, long and boolean) are not references. If you want to get a reference to one of these you need to wrap it in a class first. Java provides ready-made type-wrapper classes in the java.lang package for Boolean, Character, Integer, Double, Float, and Long. Bytes and shorts can be stored in the Integer class as well.

Read Data From A File?

There are a number of ways to read data from a file. If you're reading a file as raw binary data, you open a file using a FileInputStream(String) constructor and use one of the various read() methods to read the data into an array of bytes. For example the following program reads raw data from a file specified on the command line. It then writes the same data to the standard output.

import java.io.*;

class ReadRawData {

  public static void main (String args[]) {

    boolean done = false;
    byte b[] = new byte[1024];
    int num_bytes = 0;

    FileInputStream fin = null;
    try {
      fin = new FileInputStream(args[0]);
    }
    catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("You have to give me the name of a file to open.");
      System.exit(0);   
    }
    catch (FileNotFoundException e) {
      System.out.println("Could not open input file " + args[0]);
      System.exit(0);
    }
    catch(IOException e) {
      System.out.println("Error while opening input file" + args[0]);
      System.exit(0);
    }
    catch (Exception e) {
      System.out.println("Unexpected exception: " + e);
      System.exit(0);     
    }

    try {
      num_bytes = fin.read(b);
    } 
    catch(IOException e) {
      System.out.println("Finished Reading: " + e);
      done = true;
    }
    catch (Exception e) {
      System.out.println("Unexpected exception: " + e);
      System.exit(0);     
    }
      
    while(!done) {
      System.out.write(b, 0, num_bytes);
      try {
        num_bytes = fin.read(b);
      }
      catch(IOException e) {
        System.out.println("Finished Reading: " + e);
        done = true;
      }
      catch (Exception e) {
        System.out.println("Unexpected exception: " + e);
        System.exit(0);     
      }
      if (num_bytes == -1) done = true;
   }  // end while
    
 }  // end main
  
} // end ReadRawData
On the other hand if you're reading a text file you'll probably want to use a DataInputStream which gives you a readLine() method that returns successive lines of the file as Java Strings. You can then process each String as you see fit.

// Implement the Unix cat utility in java

import java.io.*;

class cat  {

  public static void main (String args[]) {
  
    String thisLine;
 
   //Loop across the arguments
   for (int i=0; i < args.length; i++) {
 
     //Open the file for reading
     try {
       FileInputStream fin =  new FileInputStream(args[i]);
       // now turn the FileInputStream into a TextFileStream

       try {
         DataInputStream myInput = new DataInputStream(fin);
  
         try {
           while ((thisLine = myInput.readLine()) != null) {  // while loop begins here
             System.out.println(thisLine);
           } // while loop ends here
         }
         catch (Exception e) {
           System.out.println("Error: " + e);
         }
      } // end try
      catch (Exception e) {
        System.out.println("Error: " + e);
      }
  
    } // end try
    catch (Exception e) {
      System.out.println("failed to open file " + args[i]);
      System.out.println("Error: " + e);
    }
  } // for ends here
  
} // main ends here

}
This code emulates the Unix "cat" command. Given a series of filenames on the command line it concatenates the files onto the standard output. Since this program didn't work the first few times I wrote it, I even tossed in some error checking and exception handling via try and catch.

See the Java class API documents for details of the syntax for these methods.

How do I scanf in Java?

Java has no exact equivalent to C's scanf, fscanf and sscanf functions. Roughly equivalent functionality is scattered across several classes though. You first read an input line into a string using DataInputStream.readline() as discussed in the previous question.

Next use the StringTokenizer class in java.util to split the String into tokens. By default StringTokenizer splits on white space (spaces,tabs, carriage returns and newlines) but that is user definable.

import java.util.StringTokenizer;

class STTest {

  public static void main(String args[]) {
  
    String s = "9 23 45.4 56.7";
    
    StringTokenizer st = new StringTokenizer(s);
    while (st.hasMoreTokens()) {
      System.out.println(st.nextToken());
    }
    
  }
  
}
prints the following output:

9
23
45.4
56.7
Finally you convert these tokens into numbers using the type wrapper classes as described in the next question.

How do I convert strings to numbers?

You can convert strings into numbers using the Integer, Float, Double and Long type wrapper classes as indicated by the following code snippet:

class ConvertTest {

  public static void main (String args[]) {

    String str;
  
    str = "25";
  
    int i = Integer.valueOf(str).intValue();
    System.out.println(i);
    long l = Long.valueOf(str).longValue();
    System.out.println(l);

    str = "25.6";
  
    float f = Float.valueOf(str).floatValue();
    System.out.println(f);
    double d = Double.valueOf(str).doubleValue();  
    System.out.println(d); 
  
  }
  
}
There are no equivalent Short and Byte classes. For shorts and bytes use the Integer class but use the byteValue() or shortValue() methods instead.

How do I write data to a file?

You should only assume you'll be able to write to a file from an application. Although it may be possible to write data into a file from an applet if the browser viewing the applet is HotJava, this ability will generally be disabled. From within Netscape there is no way for an applet to write to a file on the local hard drive.

Within an application, however, file access is straight-forward. There are several ways but here is a simple example using formatted output streams:

import java.io.*;

class PrintToAFile  {

  public static void main (String args[]) {

    //First open the file you want to write into
    try {
      FileOutputStream fout =  new FileOutputStream("test.out");

      // now convert the FileOutputStream into a PrintStream

      PrintStream myOutput = new PrintStream(fout);

      // Now you're able to use println statements just as if you were using System.out.println
      // to write to the terminal 

      myOutput.println("Hello There!");
      myOutput.println(1 + " + " + 1 + " = " + (1+1));
    }
    catch (IOException e) {
      System.out.println("Error opening file: " + e);
      System.exit(1);
    }

  } // main ends here

}
There are a number of other things to note about writing data to a file. This program creates or opens a file called "test.out" in the same directory as the running program. However you could pass it a full pathname to a file in a different directory instead.

You should also learn about DataOutputStreams and the write() method when you get a chance. DataOutputStreams and DataInputStreams are used for moving data between Java programs in a portable way. The various incarnations of the write() method are used for writing and reading arbitrary byte streams. What we've demonstrated here is more suitable for human consumption.

How Do I Call C Code from Java?

First of all for security reasons you can only call external code from an application. You cannot call external code from an applet. (Otherwise all the security would go out the window.) Furthermore all code you write in this way will be non-portable. If these aren't problems for you, check out javah in the Java developer's kit.

How Do I Call Java from C?

Since Java is not as of yet a true compiled language, the only way I know to call Java code from C is by using the system() call (or your OS's equivalent) to execute the java interpreter with appropriate command line arguments.

Several people have written to me with apparently different methods that involve deep, dark hacks to the java interpreter, dump and undump and other tricks. However so far I don't understand any of this.

How do you do multiple inheritance?

Use interfaces.

Alright, what's an interface?

An interface is an idea taken from Objective C. It describes the public methods that a class implements and their calling conventions without saying anything about how those methods are implemented. It is the responsibility of each class that implements an interface to provide code to handle the cases where the methods of the interface are called.

What are abstract classes?

Abstract classes are classes which leave one or more methods to be implemented by subclasses. These methods are declared but are not implemented. Each subclass of an abstract class which is not itself abstract must override the abstract methods.

An abstract class cannot be instantiated. Only its subclasses can be instantiated.

Can I write objects to and read objects from a file or other stream?

In theory yes, but once again all the coding is up to you. There is no general method for doing this. The problem is made harder by Java's security features that don't let you forge arbitrary byte streams into objects.

In the future a serialization interface will be added to the language. It is currentyl in alpha.

How do I call the native API from Java?

You can do this only in an application, not in an applet. You will need to write some intermediary code in C or another traditional language and call your C code from Java.

Programming Applets

Can applets communicate with each other?

At this point in time applets may communicate with other applets on the same page. As yet there is no way for applets on different pages to communicate directly. This may be added at some point in the future.

For applets on the same page Arthur van Hoff has provided this example:

Applet 1:

    import java.awt.*;
    public class Applet1 extends java.applet.Applet {
        public boolean handleEvent(Event evt) {
            Applet2 buddy = (Applet2)getAppletContext().getApplet("buddy");
            return (buddy != null) ? buddy.handleEvent(evt) : false;
        }
    }
Applet 2:


    import java.awt.*;
    public class Applet2 extends java.applet.Applet {
        String str = "";
        public boolean handleEvent(Event evt) {
            str = evt.toString();
            repaint();
            return true;
        }
        public void paint(Graphics g) {
            g.drawString(str, 0, size().height * 2 / 3);
        }
    }
HTML:


<HTML>
<HEAD>
</HEAD>
<BODY>

    <applet code=Applet1.class width=100 height=100></applet>
    <applet code=Applet2.class width=400 height=30 name=buddy></applet>
</BODY>
</HTML>
It is conceivable to have applets that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial. However there is currently no secure way to store this data on the client.

Can applets launch programs on the server?

Yes, using cgi. Any other implementation would be server dependent. Of course this requires a lot of coding and is non-trivial. A simple way to do this is not built into Java because that would require a special server. One of Java's strengths is that it is httpd server independent.

Can applets launch programs on the client?

Absolutely not. This would be a security hole big enough to walk three herds of elephants, two marching bands and at least one quarter of the people AT&T laid off through.

Can I record audio from an applet?

This is what is known as "a third-party opportunity". In other words not this year and probably not next year either. This would make a neat Java plug-in if anyone cares to write one in C.

How can I avoid blinking and flashing in an applet?

Flashing applets are caused by the invalidation of a section of the applet's screen space. The affected area is erased and then redrawn.

To prevent this, you need to create an Image member of your applet. Then override the update() method with one that draws to this (offscreen) Image. Finally, in your paint() method, do nothing but use Graphics.drawImage() to copy this offscreen bitmap onto the screen. All other drawing takes place offscreen in the update() method.

Language Issues

Why doesn't Java include insert your favorite feature here

The Java language has been extensively debated and argued about within Sun. Almost every language construct of existing languages has already been considered for inclusion in Java. While there may still be room for addition, it is very unlikely that your pet feature will be added to the language spec if it isn't already there. In a couple of years parameterized types may be added to the language. Otherwise the spec is pretty much frozen except for minor changes and bug fixes.

Extensions are planned for the class library though. In particular Sun is working on extensions for 3D, multimedia, telephony, improved graphics and multicasting.

Is Java CORBA compliant?

Not yet. In the future Java and CORBA will get a lot closer through NEO.

Can I cast an int to an Integer? a float to a Float?

No, in general you cannot promote a base data type like int or float to an Object such as an Integer or a Float. However the proper way to do this isn't very hard. Instead do

int x = 5;
myInteger = new Integer(x);

How do I version a class?

You don't. There is no support for versioning classes in Java nor is there likely to be in the near future. A solution to this problem will probably have to wait for the next object oriented language which will learn from Java's mistakes as Java has learned from C++'s.

Why isn't there operator overloading?

Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn't even method overloading in Java but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

Does Java pass function arguments by value or by reference?

Objects, including arrays and Strings are passed by reference. Other data types are passed by value.

What does it mean that a class is "final"?

A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some small optimizations.

Methods and variables may be declared final as well. This means they may not be overridden in a subclass.

It's also possible to make a static variable final to get the effect of C++'s const statement or some uses of C's #define, e.g.

public static final int myVar = 0

What does it mean that a method or variable is "static"?

Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.

Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work.

Are there parameterized types?

Not in the first iteration of the language. However this is being seriously considered for future versions.

How does garbage collection work?

Current implementations of Java uses a mark and sweep garbage collector. Reference counting is not used. Thus circular linked lists do not lead to memory leaks. It is theoretically possible that future versions of Java will use some other garbage collection algorithm.

PERFORM and BECOME

Sorry Smalltalkers. There's no equivalent for PERFORM or BECOME in Java. These would probably open security holes. There are workarounds for some things you might want to do using interfaces.

What are peer "classes"?

Peer classes exist mainly for the convenience of the people who wrote the Java environment. They help in translating between the AWT user interface and the native (Windows, OpenWindows, Mac etc.) interfaces. Unless you're porting Java to a new platform you shouldn't have to use them.

The Java Class Library

java.awt

What Does AWT Stand For?

So far I've heard it claimed that AWT stands for:

I do not know which if any of these are correct, but Abstract Window Toolkit seems to be the most popular.

Clipping

java.awt.Graphics.clipRect(int, int, int, int) and related methods are hopelessly flawed, at least as of 1.0. Ignore them completely.

Instead if you need to do clipping, create separate offscreen Images for each clipping region. Each Image should be the size of the clipping region you desire. Draw into those offScreen Images, and then copy them onto the appropriate section of the of your applet window using java.awt.Graphics.drawImage(). Some coordinate conversion will almost certainly be necessary.

If the background image isn't a simple color then you'll first need to copy the appropriate part of that image to your offscreen clipping Image. You can do this by drawing your background Image into your offscreen region with Graphics.drawImage and a suitable shifting of coordinates.

This all works for rectangular regions only since all Images are rectangular. More complicated geometries can be faked if all but one section contains only simple colors.

java.net

How do I convert a numeric IP address like 199.1.32.90 into a hostname like star.blackstar.com?

Unfortunately due to an unintended side effect (i.e. a bug) in Java's caching of IP addresses and hostnames, you can't convert numeric IP addresses into hostnames as of 1.0.2. This may be fixed in a future release.

java.util

How random is Random()?

It's good enough for games. I wouldn't use it for cryptography.

Unlike most random functions in other libraries the Math.random() method seeds itself with the current time in milliseconds. Thus you do not need to seed it explicitly at the start of your program. If you require a non-random Random() for test purposes or you need more randomness than the current time in milliseconds can provide, then you can use java.util.Random() which has a constructor that lets you specify a seed.

Common Errors and Problems

How Can I Avoid Flicker in an Applet?

The key to fixing flicker is realizing that the screen isn't actually painted in the paint() method. The pixels get put on the screen in the update() method which most applets don't overrride. However by overriding the update method you can do all your painting in an offscreen Image and then just copy the final Image onto the screen with no visible flicker.

The cookbook approach is simple. Add the following three private member variables to your applet and the public update method. Flicker will magically disappear.


  private Image offScreenImage;
  private Dimension offScreenSize;
  private Graphics offScreenGraphics;

  public final synchronized void update (Graphics g) {

    Dimension d = size();
    if((offScreenImage == null) || (d.width != offScreenSize.width) ||  (d.height != offScreenSize.height)) {
      offScreenImage = createImage(d.width, d.height);
      offScreenSize = d;
      offScreenGraphics = offScreenImage.getGraphics();
    }
    paint(offScreenGraphics);
    g.drawImage(offScreenImage, 0, 0, null);

  }

Can you explain CLASSPATH?

Most Java applets and applications aren't self-contained. They need to get access to other classes to do their work. For instance when you call System.out.println() java needs to know where to look to find the file that includes the System package.

The CLASSPATH is an environment variable that defines where Java looks for these imported classes. If the CLASSPATH isn't set properly every program written in Java won't be able to run.

Thus when you import java.applet.Applet java tries to find the relevant code in $CLASSPATH/java/applet/Applet

If there are multiple directories in $CLASSPATH then each of them will be searched in order from left to right. In Netscape you should make sure that the first directory in CLASSPATH. is the directory that contains netscape's class files (The defaults are /usr/local/netscape/java/classes on Unix and C:\NETSCAPE\NAVIGATOR\Program\java\classes in Windows.)

Netscape gives me "Applet Not Initialized Error"

Make sure your CLASSPATH environment variable is set to point to the directory containing the class file. Under Unix this is done with the command

setenv CLASSPATH my_class_directory
Under Windows this is set by adding the line

     SET CLASSPATH=C:\JDK\JAVA\CLASSES;
to your autoexec.bat file. You can of course point it at a different directory, but then your classes should reside in that directory.

If the class is part of a package then it needs to be in the appropriate subpath of the CLASSPATH directory. For instance if your class is part of package foo.bar, then it should be in $CLASSPATH/foo/bar.

Other Netscape Problems

As of version 2.0 Netscape has many problems handling Java applets.In no particular order they are:

I keep getting access privilege violations, " Java tried to read file foo.class in directory bar."

This happens when you try to load a class from a local hard disk instead of a server, the class is not a subclass of Applet, and the directory where the class resides is not in the HotJava read path. The solution is to move the class file into a directory in the HotJava read path. On Unix one such directory is ~/public_html/classes (where ~ is your home directory). Alternatively you can change the HOT_JAVA_READPATH environment variable to point to the directory containing your classes directory.

Javac keeps insisting that it can't find the right constructor function in my class, but I'm sure it's in a file I imported. Why is it even looking in my class instead of the imported file?

You cannot construct instances of a class on the fly using syntax like

System.out.println(Double(0.56).toString());

You must use the new operator like:

Double myDouble = new Double(0.56);
System.out.println(myDouble.toString());
or

System.out.println((new Double(0.56)).toString());
In other words, constructors are only called after a new operator.

Security

System Level Security

On a system level Java applets live in a cage. They can do pretty much anything they want inside their cage, but they cannot get outside the cage and do damage unless the user unlocks the door to the cage. Even then they wear shackles that prevent them from doing things like writing to arbitrary addresses in memory.

In Netscape the user doesn't even get the keys to the cage so you can't let the applets out into your system even if you wanted to. With the Applet Viewer it is possible to give your applets more access to the system. However they still can't do everything a C program can do.

Specifically a Java applet cannot write anything to a hard drive without permission. It cannot write directly to memory, and it cannot introduce a virus into your system. A Java applet can use a lot of your CPU time though not 100% of it. It cannot crash your system (though a Java enabled browser can).

User Level Security

A Java applet can trick the user into doing something stupid such as revealing their root password though there are efforts to avoid this. A Java applet can also send this information back to the applet's server.

Finally an applet can display pictures or text or play sounds which the user may find annoying or offensive, but this hardly qualifies as a security flaw and is not unique to Java enabled browsers.

Tools

IDE

Symantec has released Cafe, an applet development enivronement for Windows 95, NT and the Mac. It includes a source code editor and a class browser, and a just-in-time compiler. It is still beta quality at best. I do not recommend it

Natural Intelligence's Roaster is a PowerMac hosted applet development environment. It has been designed from the public specs with no help from Sun. It is still alpha quality. I do not recommend it.

Metrowerks added Java support to Code Warrior 9 for the Mac in May, 1996. Metrowerks has licensed Sun's source code. The Java support is alpha quality, and is not by itself worth the price of Code Warrior, even the $99 Java only edition. However if you also need a C compiler it doesn't cost you anymore to get Java support.

Sun has announced a payware IDE currently referred to as "Solstice Workshop". It is currently in public beta test, but is probably not worth the download time yet. Solstice Workshop is similar to Sun's existing Workshop products for Fortran and C++. However it is written entirely in Java.

Aleda Freeman has created an excellent page on Java IDE's and other tools at http://www.cybercom.net/~frog/javaide.html. This site has descriptions of and links to IDE's, database connectivity tools, and more.

Debugger

A preliminary jdb is available with the beta.

Editors

An emacs mode for Java is available at ftp://ftp.javasoft.com/pub/java/contrib/emacs/

YACC grammar

You can ftp one from ftp://iecc.com/pub/file/java-grammar.shar.gz

Profilers

javaprof

The Java Virtual Machine and Byte Codes

The most recent Java Class File / Java Virtual Machine specs are available in various formats from http://www.javasoft.com/java.sun.com/newdocs.html

Can I program directly in byte code?

In theory, yes, you can. There are no tools to help you do so. You need to use a tool that lets you write bytes to a file like Norton Disk Editor. The Java interpreter will check your byte codes to make sure they don't violate security. If you write security violating byte codes the interpreter won't run them.

Optimizing Java

  1. Make your classes final.
  2. Use the -O flag to the compiler.
  3. If you're reading data off a disk read it in as large a chunk as possible. Do not read it a byte at a time. If you need to process the data a byte at a time read it into a temporary buffer first.

Legal Issues

Some portions of Java and HotJava are neither in the public domain nor copylefted. However no license is required to write and distribute most Java applications and applets. Nor is any license from Sun is required to distribute the Java or HotJava in binary form.

The Java source code is freely available for non-commercial use though a license must be signed. If you want to license the Java source code for commercial use you will need to pay $125,000 for the first platform, $25,000 per additional platform and a $2/unit royalty. Annual upgrades are $50,000 plus $5,000 for each additional platform. Complete details are at http://www.javasoft.com/java.sun.com/source.html.

Furthermore whether your product is commercial or non-commercial you may not use the trademark "Java" to describe your product unless you pass an as yet unreleased verification and test suite.

FAQ's about the FAQ

Who is this Elliotte guy, and just what qualified him to write a Java FAQ anyway?

He was willing to do it. Seriously months on the Java mailing lists made it obvious that a FAQ was needed and since none seemed to be forthcoming from those more qualified than I, I boldly and with a complete disregard for my absolute lack of qualifications stepped forward and volunteered. I do have some hope that my previous experience with FAQ lists, the world wide web and a variety of programming languages may somehow cover up the fact that I have no idea what I'm doing. You've read the FAQ list by now. Did I succeed?

Why am I taking on such a Herculean task? It's often said that you never really understand a subject until you teach it. I'm going to endeavor to learn Java and understand it by teaching it. The result should be interesting at least. Since I'm very new to Java and clearly do not yet understand the language, I'll have a perspective on the issues that should be helpful to newcomers.

Are there mistakes here? Absolutely. I hope people here and elsewhere will correct me gently and help lead me on the path to true Java enlightenment when I err. And if they aren't so gentle, well, I've developed a pretty thick skin after five years of Usenet.

My companion tutorial in how to write Java is going to reflect the programs I'm actually writing. As I learn to do a Hello World program, I'll write about Hello World. (OK, I've actually already gotten beyond Hello World but not much beyond.) How fast the FAQ list grows will depend in large part on how fast my skills grow. You'll get to watch me learn, make mistakes, correct mistakes and so on.

There may be an advantage to this approach. People who want to learn Java will be coming from almost identical places as me. I always hate having to write down or talk down to people, and I don't do it very well. Similarly I find it frustrating to try to communicate with people who are way beyond me (as obviously some people on the Java mailing lists are). Right now I am at the level of the lowest of the low. This means that I can write for people without much prior experience without boring myself or, hopefully, my audience, to tears.

Finally I'll emphasize that I'm not trying to prevent anyone else or any other team of people from taking on a similar project. I hope someone does. I'll probably learn from what they do, and they'll learn from what I do, even if it's only to learn the sorts of things novices are confused about. And of course not everyone shares the same learning style so while some people may enjoy my approach to Java I am sure others will find it dense, incoherent and ultimately incomprehensible. More choices are better.

Ultimately I'm doing this because I think Java is very, very cool and I am convinced I need to learn it sooner rather than later. I think this project will propel my Java knowledge forward, and if it does that I'll consider my project a success. If I can help a few other lost souls to climb out of the pit with me at the same time, so much the better.

Why don't you include X in your FAQ?

Please do make suggestions about topics for FAQ list inclusion. You can email them to elharo@sunsite.unc.edu. I do follow comp.lang.java, and have a pretty good idea of what's discussed there. However I don't necessarily understand all the conversations that take place on it. I am not a Java genius, at least not yet, and a FAQ is far more likely to be included here if you propose not only a question but also an answer. Please be as clear and explicit with your answer as possible so that even someone with as small a brain as I can understand it. Thank you.

This is really cool. Can I republish or translate it?

This FAQ list and its entire contents are copyright 1995, 1996 by Elliotte Rusty Harold. If you have specific desires to republish it in whole or part contact me at elharo@sunsite.unc.edu and tell me exactly what you want to do. I'm generally receptive to non-profits that want to make it available to the public at no charge and to anyone who's willing to make reasonable payment arrangments.

However I do not allow the FAQ list, either the text or HTML version, to be placed on any web sites but my own. Mirroring HTML files is a fundamentally bad idea that is at cross-purposes with the design of the web. Among other problems it makes maintaining up-to-date copies phenomenally difficult. If you think this file would be a useful addition to your web site, then link to it. That's the way the web is designed. Not all information needs to reside in one central location. No permission is needed to link to this or any other of my HTML files. In fact I'd prefer it if you'd not ask me, since then I don't have to spend time answering you.

Although there's more reason to want to translate the document rather than merely mirror it, I regret that I do not have the time or resources to support any translation efforts. This document will be available in English only for the foreseeable future.

If you want to use the source code samples included here, please do. I consider the source code (though not the FAQ list itself!) to be public domain with the exception of the two samples from Arthur Van Hoff. (You'll have to ask him about them.) No permission is necssary to reuse, edit, modify or publish any of my source code contained in this FAQ list.

Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu

[Cover][Table of Contents][Java Tutorial][About the book][Java links][Java FAQ][Newsletter][Ordering info]

Home



© Prentice-Hall, Inc.
A Simon & Schuster Company
Upper Saddle River, New Jersey 07458

Legal Statement