comp.lang.java.programmer FAQ

Version: comp.lang.java.programmer FAQ list Apr 13 1997, Peter van der Linden.
HTML markup by John English.
Peter van der Linden, the author of this FAQ, is a software engineering manager in the OS kernel group at Sun Microsystems in California. He attended Manchester University, England, where he graduated in 1980 with a first in Computation. He still has a big head about it.

He is the author of "The Official Handbook of Practical Jokes" published by NAL-Penguin (now out of print) and 3 books on programming:

"Just Java" is the only book on the market that teaches you a new programming language, features a recording of the Anti-Barney on the CD, and also shows you how to fold the "Origami Kami-Kaze water bomber".

Most of the entries on this Java FAQ list are intended for experienced programmers. To distinguish it from other Java FAQs, this is termed the "Programmer's FAQ" and will be posted mostly in comp.lang.java.programmer.

Latest copy of this FAQ is available at: http://www.best.com/~pvdl


TABLE OF CONTENTS

0.   LOOKING FOR INFORMATION 1.   LANGUAGE ISSUES 2.   APPLETS and AWT 3.   CORE LIBRARIES 4.   NETWORKING & DISTRIBUTED OBJECTS 5.   Java IDIOMS 6.   MULTI-MEDIA 7.   SECURITY 8.   FURTHER RESOURCES Acknowledgements


0. LOOKING FOR INFORMATION

0.0 Where can I find a list of Java books and book reviews?

http://lightyear.ncsa.uiuc.edu/~srp/java/javabooks.html

0.1 How do I search Deja News for past postings on Java topics, e.g. the FAQ?

Go to http://www.dejanews.com/forms/dnsetfilter.html Under "Newsgroups" enter "comp.lang.java.programmer" (or whatever) Under "Subject" enter "Frotteur" (or other topic you find pressing) Click "Create Filter" It will go to a new document, and you should click the link labelled "nnn Documents" ("nnn" is some number).

This makes finding information very easy. Also look at http://asknpac.npac.syr.edu/ for Java newsgroup search.

0.2 How do I check on known bugs in JDK 1.1?

Look at http://java.sun.com/products/jdk/1.1/knownbugs/index.html

0.3 How do I translate C/C++ into Java or vice-versa?

In general it is not simple to translate C/C++ into Java, as Java lacks the arbitrary pointer arithmetic of those languages. If your C code does not use pointer arithmetic, automatic translation gets a lot simpler. [anyone who has URLs of translation tools, please send them]

Going the other way there are currently three freely-available tools to translate Java into C. If I understand it correctly these have been done for hacking value, rather than practical purposes.

None of them support the AWT yet, and both j2c and JCC have additional restrictions.

There's a product to convert Visual Basic to Java. Details at http://www.blackdirt.com and http://www.tvobjects.com

0.4 Is there a Java port to Windows 3.1?

IBM's ADK1.02 beta 3 is available at the following locations:

http://ncc.hursley.ibm.com/javainfo/latest/answers/faq0.html
http://www.alphaworks.ibm.com/formula

Netscape Navigator for Win3.1 has Java support [anyone know the version?] Microsoft is preparing a Win3.1 port of the JDK.

You should also consider JavaSoft's "Project Rescue" $100 kit that converts a PC into a thin client Java system. Details are sparse as yet, but this is probably more for business users than personal PCs.

Lists of JDK ports are available from ?? [URL anyone?]


1. LANGUAGE ISSUES

1.1 Why doesn't my "hello world" program work?

Two very common causes of failure are:

1.2 How can I program linked lists if Java doesn't have pointers?

Of all the misconceptions about Java, this is the most egregious. Java has pointers (it calls them "references"). It does not have pointer arithmetic or untyped casting. By removing the ability for programmers to create and modify pointers in arbitrary ways, Java makes memory management more reliable, while still allowing dynamic data structures. Also note that Java has NullPointerException, not NullReferenceException.

A linked list class in Java might start like this:

      public class linkedlist {
          public linkedlist head;
          public linkedlist next;
          public linkedlist next(linkedlist current) { ...
      ... }
Another choice for a linked list structure is to use the built-in class java.util.Vector which accepts and stores arbitrary amounts of Object data (as a linked list does), and retrieves it by index number on demand (as an array does). It grows automatically as needed to accommodate more elements. Insertion at the front of a Vector is a slow operation compared with insertion in a linked list, but retrieval is fast. Which is more important in the application you have?

1.3 What is the true story about how parameters are passed in Java? Is it by value or by reference?

All parameters (values of primitive types, and values that are references to objects) are passed by value [JLS sect 8.4.1]. However this does not tell the whole story, as objects are always manipulated through reference variables in Java. Thus one can equally say that Objects are passed by reference (and the reference variable is passed by value). This is a consequence of the fact that variables do not take on the values of "objects" but values of "references to objects".

Bottom line: primitive type arguments (int, char, etc) do not change when the corresponding parameter is changed. The fields of object type arguments do change when the corresponding parameter fields are changed.

1.4 Why the *&%$# is String final?

There are several reasons. The simplest is that being final guarantees that instances of String are immutable. (The String class implements immutable objects, but if it were not final it would be possible to write a subclass of String which permitted instances to be changed.) But that's an unsatisfying answer, because the real question is "Why must Strings be immutable?"

One reason is efficiency. It's easier to optimize accesses to an object that is known to be immutable. Strings are very commonly used, even used behind the scenes by the Java compiler. Efficiency gains in the String class can yield big dividends.

A more compelling reason is security. Before String was changed to be final (while Java 1.0 was still in beta) there was a race condition which could be used to subvert security restrictions. It had to do with having one thread change a pathname while another thread was about to open it.

There are other ways to solve these problems, but making String final is the one that the designers chose.

1.5 How are finalizers different from C++ destructors?

Java objects are not explicitly deleted and do not have destructors. Instead they are implicitly garbage collected when the JVM realises your program can no longer access them. Typically this technology is not based on reference counting and will cope with circular references.

Every object has a routine called finalize() which will be called before the object is collected. This is Java's nearest equivalent to C++'s destructor. However, it is not a good idea to rely on finalisation for the timely freeing of resources.

This is because garbage collection and hence finalization may be arbitrarily delayed, and may never happen at all if the program terminates before it runs out of memory. You should instead provide your objects with methods similar to Graphics.dispose() to free resources, and call the dispose() method explicitly when you have finished using them - typically within the "finally" clause of a "try/catch" block. You may then call your dispose() method from within your finalize() method as a last-ditch attempt to free the resource if someone forgets.

Alas, all this means the C++ idiom of "object construction is resource aquisition" does not translate well to Java. However, note that 90% of destructors in C++ are there to free memory, and the GC means you don't need to do that in Java. As well as fixing an important source of bugs, the GC is essential to Java's security model; without it you could forge object references by preserving the reference after the object has been deleted.

If your program appears to be crashing due to running out of some system resource (like File, Window or Graphics handles), it probably because the system is running out handles before it has run out of memory. Check that you have called the dispose() method (or equivalent) on every object that uses system resources. You can help the GC a little bit more by explicitly NULLing out references that you've finished with.

1.6 What happened to "private protected"?

It first appeared in JDK 1.0 FCS (it had not been in the Beta's). Then it was removed in JDK 1.0.1. It was complicated to explain, it was an ugly hack syntax-wise, and it didn't fit consistently with the other access modifiers. More people disliked it than liked it, and it added very little capability to the language. It's always a bad idea to reuse existing keywords with a different meaning. Using two of them together only compounds the sin.

1.7 What's the Java equivalent of sizeof()?

A: There isn't one. sizeof() in C and C++ is used in three main places:

  1. To check on the size of a primitive type. In Java, the sizes of primitive types are fixed in the language specification (a short is always 16 bits; an int is always 32 bits, etc), so this is no longer necessary.
  2. In memory allocation (e.g. malloc (32 * (sizeof(int));) In Java you always allocate a specific type of object, rather than a block of raw memory that you will fill as you like. The system always knows the size of the kind of objects you are allocating. So sizeof is not needed.
  3. in pointer arithmetic (e.g. p += sizeof (int)) Pointer arithmetic of this type is not allowed in Java, so this isn't necessary, either.
For all these reasons, there is no need for a Java sizeof() operator.

1.8 I extended the class called Frotz, and the compiler is giving me an error message "No constuctor Frotz()" in the child class. Why?

When you define a constructor for a class, unless you explicitly call the superclass's constructor at the start, a call to the superclass's parameterless constructor is implicitly inserted. The problem you're seeing is what happens when the superclass doesn't have a parameterless constructor. The solution is usually to call the correct version of the superclass's constructor with the right parameters.

1.9 Why does <unexpected> happen in Java floating point?

There are several unexpected things that seem to bite programmers with floating point. Usually this is a result of the programmer not being fully conversant with FP. There is one limitation of FP in JDK 1.0 (fixed in JDK 1.1). Namely, when you output a floating point number in Java 1.0, the result is system-dependent and contains no more than six digits after the decimal point. This bug is fixed in Java 1.1.

If you seem to be having other problems with floating point, your problem probably stems from the fact that floating-point arithmetic is inherently imprecise. You can expect up to 7 digits of precision with floats and 16 digits with doubles.

Additionally, when Java converts floating point numbers to a String, as is done when they are output, enough digits are printed so the number can be read back in with no loss of precision. For this reason, you may see more "inaccuracies" in floating point output than you are used to. This policy actually gives you more consistent results than on a system where floating point output is deliberately rounded to make the output "pretty".

For more information and detailed specifications on how Java deals with floating point, see the following URLs:

http://www.javasoft.com/products/jdk/1.1/compatibility.html#incompatibilities
http://www.javasoft.com/doc/language_specification/javalang.doc.html#1466
http://www.javasoft.com/doc/language_specification/javalang.doc.html#5899

If you want the rounded floating point output that most languages have, use the new java.text package of Java 1.1 to limit the number of digits that are output. If you need more precision than about 16 digits, use the BigInteger and BigDecimal classes of Java 1.1.

1.10 Why do I get this compiler error message?

     urltest.java:8: Variable test may not have been initialized.

     URL test; 
     try {   test = new URL("http://osprey.avs.dec.com");
     } catch (MalformedURLException e) {}
             System.out.println("this is url " + test);
     }
If an exception is raised in the try clause, test will not be given a value, yet you are using it in the catch clause. The solution is either to declare test with an explicit initial value of null, or (better) to print out the e.getMessage() string of the exception.

1.11 Why do I get this compiler error message?

   public static void main(String[] args)  {
                                            ^
                                            Statement expected.
       public static final float Conversion_Factor = 39.37; 
       ^
       Type expected.
Variable declarations inside are never given the "public", "static", or "final" keywords. They are not public or static because they are local to a method. They are not final by convention. Move your constant declarations outside the method. They are usually put at the beginning of the class.

1.12 How do I transform a char into the corresponding int value, that represents the code value of the char?

    char c = 'A';
    int  i = c;
Going the other way is just c = (char) i;

[I don't understand why this question crops up so frequently! Can anyone explain what language or book is confusing people on this apparently straightforward topic?]


2. APPLETS and AWT

2.1 My applet works on my machine, but fails when I put it on our web server. Why?

It could be one of several reasons, and unfortunately the messages that you get in this situation aren't much help. In general, you can assume that either your applet's class files are corrupted somehow, or the web server can't find one or more of them when the browser needs them.

Be careful of the following things:

2.2 Why do I get this when using JDK 1.1 under X Windows?

     java.lang.NullPointerException
         at sun.awt.motif.MFramePeer.(MFramePeer.java:59)
         at sun.awt.motif.MToolkit.createFrame(MToolkit.java:153)
         at java.awt.Frame.addNotify(Frame.java)
         at java.awt.Window.pack(Window.java)
There's a missing font on your system. Move font.properties from the "lib" subdirectory aside to font.properties.bak Then it won't look for the font and fail to find it.

The problem occurs because the Motif AWT libraries use the Font "plain Dialog 12 point" as a fall-back default font. Unfortunately, when using a remote X server sometimes this font isn't available.

2.3 How do you make the applet's background transparent?

There is no way to give an applet a transparent background that lets the web browser background show through. You can simulate it by giving the applet a background that matches the underlying browser background. It doesn't produce satisfactory results with a patterned background because of problems aligning the edges.

2.4 How do you do file I/O from an applet?

The following suggestions are for server-side I/O.

  1. Read a file by opening a connection using the URL class and then using a DataInputStream to read the data. This allows reading but not writing. It requires an http demon running on the server, which will usually be the case.
  2. Or open a socket back to the server and read/write the data. Have a process on the server that listens for socket connections from applets and does the requisite I/O. This does I/O on the server.
  3. Or use a CGI script or servlet on the server to write when browsed. There is some source at ftp://ftp.oyster.co.uk/pub/java/fileIO/
The following suggestions are for client-side I/O.
  1. Use a trusted applet (see section on security). This will eventually permit local I/O.
  2. Or use a browser that has a security policy that is configured to allow file I/O (such as Sun's appletviewer).

2.5 Why is GridBagLayout so hard to use?

GridBagLayout was contributed to Javasoft by a programmer who wanted to support the Java effort. It was intended as a proof that the AWT offered enough features for programmers to write their own layout managers. It wasn't designed with human factors and ease of use in mind. If it bothers you (it bothers me) then just don't use it. Create your GUI on several panels and use the other layout managers as appropriate to get the exact effect you want. The official story from the project leader of the AWT project, as explained to the Mountain View Java Users' Group on Dec 4 1996, is: The case has been made and is now accepted that GridBagLayout is too hard to use for what it offers. GBL will continue to be supported, and something better and simpler will eventually be provided as well. This "better GBL" can be used instead of GBL.

Bottom line: nobody has to waste any effort on GBL, there are better alternatives available now, and more on the way.

2.6 How do you change the font type and size of text in a TextArea?

    myTextArea.setFont(new Font("FONTNAME", FONTSTYLE, FONTSIZE));

where FONTNAME is the name of the font (eg Dialog or TimesRoman). FONTSTYLE is Font.PLAIN, Font.ITALIC, Font.BOLD or any combination (e.g. Font.ITALIC+Font.BOLD). FONTSIZE is the size of the font, e.g. 12.

2.7 How do you determine the screen dimensions in an applet?

    Toolkit.getDefaultToolkit().getScreenSize()

2.8 How do you use an image as the background in applets?

Create a Panel or Canvas for the background, and draw the image in the normal way.

2.9 How do you get a MenuBar/Menu in an applet?

In your applet's init() method, create a Frame instance and then attach the Menus, Menubar etc to that frame. You cannot attach the Menu or a Menubar to an applet directly.

Or get the parent Frame like this:

        Container parent = getParent();
        while (! (parent instanceof Frame) )
                parent = parent.getParent();
        Frame theFrame = (Frame) parent;
This second suggestion probably won't work on Macs (where would the menubar go?) or in some browsers.

In JDK 1.1, just use a popup menu, which isn't attached to a Frame.

2.10 Is it possible to draw a polygon or a line more than 1 pixel wide?

JDK 1.1.1 doesn't have support for this. The standard workaround for drawing a thick line is to draw a filled polygon. The standard workaround for drawing a thick polygon is to draw several polygons.

2.11 What is the difference between an application, and applet and a servlet?

An application is a standalone program. An applet is a downloadable program that runs in a web-browser. Typically an applet has restricted access to the client system for reasons of security. A Servlet is an application, but (like an applet) requires a context in which to run, namely web-server software. Servlets are used like CGI, but allow you to use Java everywhere. The Web Server (Jeeves is the only one that currently supports Servlets) starts them up when it starts, and now your applets have something that they can talk to (via sockets) on the server that can write files, open connections to other servers, or whatever.

When I write "Jeeves" please understand I mean "the software formerly known as 'Jeeves' but now for trademark reasons known as something else."

2.12 I use Applet.add(Component) to add objects to the Applet. Is there any way to explicitly set the z-order of these objects?

Neither JDK 1.0 nor 1.1 has a way to explicitly set the z-order of components. You can try it heuristically, based on the browser you're using, or use CardLayoutManager.


3. CORE LIBRARIES

3.1 I can't seem to change the value of an Integer object once created.

Correct. Integer (Float, Double, etc) are intended as an object wrapper for a specific value of a number, not as a general purpose way of shipping a primitive variable around as an Object. If you need that it's easy enough to create: class general { public int i; }

3.2 How do I print from a Java program?

Use the Toolkit.getPrintJob() method

      PrintJob pj = getToolkit().getPrintJob((Frame) parent, "test", null);
      Graphics pg = pj.getGraphics();
      printAll(pg);
      pg.dispose();
      pj.end();
This feature was introduced with JDK 1.1. A common place to put this is in the code that handles a button press. There's no easy way to print in JDK 1.0.2.

3.3 Is there any package in Java to handle HTML?

No, Java does not have a core library widget that automatically formats HTML. At least one person has written one though. Search at http://www.gamelan.com or http://www.yahoo.com for details.

3.4 Why don't Dialogs work the way I want them to?

Modal dialogs (dialog windows that stay up until you click on them) are buggy in many browsers and in the 1.0.2 JDK. One bug is that the dialog is not necessarily put on top when it is displayed. Most of the modal dialog bugs are fixed in JDK 1.1.

3.5 Where can I find information about the sun.* classes in the JDK?

You're not supposed to. Those classes are only to support functions in the java.* hierarchy. They are not part of the API, and won't be present in Java systems from non-Sun vendors. Some people have reverse engineered the code and published an API for these classes but you use it at your own risk, and it may change without warning.

Worst of all, those programs will not have the portability of true Java but will only run on Sun JDKs. For the same reason you shouldn't use classes outside the java.* packages when using JDKs from other vendors.

3.6 How do you read environment variables from with a Java program?

Environment variables are not used in Java, as they are not platform portable. The Mac doesn't have environment variables for example. Use properties instead. Additionally, on some systems you can set a property from the command invocation line like this:

    java -Dfoo=$foo MyClass       (Unix)
or
    java -Dfoo=%foo% MyClass      (MS-DOS)
This sets the "foo" property to the value of the environment variable foo.

3.7 How do you use the Date class to display the current time in my timezone? Date.toString() always uses PST. [jdk 1.1] (Pacific Standard Time -- the zone covering California where JavaSoft is).

To make things easier for debugging Sun has decided that the toString() method should always use one format, if you want a different format you should use the new internationalization routines.

As a Date is stored internally in GMT the obvious choice for a standard format is in PST time (this is known as "irony"). As an example of how the new method should work jdk1.1/src/java/util/Date.java contains the method:

    public String toGMTString() {
        DateFormat formatter
            = new SimpleDateFormat("d MMM yyyy HH:mm:ss 'GMT'",
            Locale.US);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
        // + 1 is to work around bug in GregorianCalendar
        // XXX - need FIX
        // should probably be formatter.format( this );
        return formatter.format( new Date(getTime() + 1) );
    }
It should be reasonably straight forward to adapt this code for your prefered format and timezone.

3.8 How do I get Java talking to a Microsoft Access database?

Use the JDBC-ODBC bridge. It is not especially challenging to set up, but it does require painstaking attention to detail. There is a step-by-step example in the van der Linden text "Just Java 2nd Ed." Also check the JDBC FAQ listed at the end of this document.

3.9 How do I do stuff like scanf and sscanf in C/C++?

You can break a string like "5 loaves 2 fishes" into its parts by using java.util.StringTokenizer. This is the Java equivalent of sscanf().


4. NETWORKING & DISTRIBUTED OBJECTS

4.1 Should I use CORBA in preference to RMI? Or what?

If your distributed programs are all in Java, then RMI provides a simpler mechanism that allows the transfer of code, pass-by-value of real Java objects, and automatic garbage collection of remote objects. If you need to connect to legacy C++ (or other language) systems or you need CORBA-specific services, then CORBA is your choice.

4.2 Why does hang for a couple of minutes if my Windows PC is not dialled up to the Internet?

Java has networking support built in. When the Java program starts the Winsock dll automatically gets loaded. The first thing this does is to try to resolve the fully qualified domain name for your machine under the name "localhost". If your system doesn't have this name mapped, it will try to query a nameserver on the internet, which is typically (on a PC) your dialup ISP. So it either prompts you to connect to the ISP, or waits till the attempt times out.

You can avoid the problem by giving your system another way to resolve DNS names. Edit the hosts file for your system (found in %windir%\hosts on Win95 and %windir%\system32\drivers\etc\hosts on NT) so that localhost and the full domain name are both mentioned. So if my system is called goober.best.com change the hosts file from

   127.0.0.1  localhost
to
   127.0.0.1  goober.best.com    localhost

[If any networking guru's have improvements to this process, send'em in!]

4.3 If I call the InetAddress.getByName() method with an IP-address-string argument, like "192.168.0.1", I get an unknownHostException on some platforms, but not others.

Code like

   Socket sock = new Socket("155.152.5.1", 23);
triggers the exception. Why?

This is a platform difference that arises out of different semantics in the underlying network libraries, and is [said to be, but subject to confirmation] fixed in JDK 1.1. On Solaris and Windows NT, the IP address string only works for IP addresses that have an associated hostname. On Linux and Windows 95, the IP address string works in all cases. http://www.cdt.luth.se/~peppar/java/InetAddress/ has a workaround.

When InetAddress is instantiated with an IP address, a reverse DNS lookup is done. If the IP address is not associated with a valid hostname, the instantiation will fail. This is part of anti DNS-spoofing, and in JDK 1.1 works because the reverse lookup will not occur until the hostname is asked for. So in JDK 1.1,

        InetAddress in = InetAddress.getByName("155.152.5.1");
should always work.

[Note: this info is still to be confirmed. Net guru's?]

4.4 I am using JDK 1.1.1 on Windows95, and when I start jdb I get:

    "Uncaught exception: java.lang.UnsatisfiedLinkError no winawt 
     in shared library path"
The same program works OK using jdk1.1

It sounds like your java\bin directory is not on your PATH and so the system can't find the winawt DLL.

But actually, the problem is that Sun linked some or all of the _g code with MSVCRTD.DLL, the debug version of the VC++ runtime. You have to get that library from somewhere (like, say, VC++) in order to get jdb to run.

You'll hit this problem any time you try to debug 1.1.1 code with jdb on a win95 system that doesn't have VC++ (or the MSVCRTD.DLL library from some other source) installed. At least this is a problem you can solve without waiting for the next release.


5. Java IDIOMS

5.1 How do I convert a String to an int?

There are several ways. The most straightforward is:

   int i = Integer.parseInt();
or
   i = Integer.parseInt(,);

Note: there are similar classes for Double, Float, Long, etc.

   int i = Integer.valueOf(my_str).intValue();
also works but involves the creation of an extra object.

5.2 How do I convert an int to a string?

   String s = String.valueOf(i);
or
   String s = Integer.toString(i);
or
   String s = Integer.toString(i, radix);
or
   String s = "" + i;  // briefer but may result in extra object allocation.

Note: there are similar classes for Double, Float, Long, etc.

5.3 How do I write to the serial port on my PC using Java?

If the port exists as a pathname in the filesystem, you can open it as a file and read/write. The bigger problem is if you wish to change the characteristics of the port (e.g. baud rate, parity, etc). Java currently offers no portable way to do this. You will need to use a native method, or execute a system command. At least one company has written a library to drive the port on Windows 95, NT, OS/2. See http://www.sc-systems.com

5.4 How do I append to a file?

First, do this:

     RandomAccessFile fd = new RandomAccessFile(file,"rw");
     fd.seek(fd.length());
Then write using fd.

5.5 How can you send a function pointer as an argument?

Simple answer: use a "callback". Make the parameter an interface and pass an argument instance that implements that interface.

    public interface CallShow { public void Show( ); }

    public class ShowOff implements CallShow {
	public void Show( ) { .... }

    public class ShowMe implements CallShow {
	public void Show( ) { .... }

    public class UseShow { CallShow callthis;
	UseShow( CallShow withthis ) { callthis = withthis; }
	void ReadyToShow( ) { callthis.Show( ); }

    // in some other class that uses all this stuff:
    UseShow use_1 = new UseShow( new ShowOff() );
    UseShow use_2 = new UseShow( new ShowMe() );
and then the ReadyToShow() method on use_1 or use_2 will call the appropriate method, as if you had stored a pointer to the method.

5.6 How do I execute a command from Java? How do I do I/O redirection in Java using exec() ?

This solution works on Unix platforms using either JDK 1.0.2, or JDK 1.1. The trick is to use an array of Strings for the command line:

     String[] command = {"/bin/sh", "-c", "/bin/ls > out.dat"};
If you don't do this, and simply use a single string, the shell will see the -c and /bin/ls and ignore everything else after that. It only expects a single argument after the -c.
     import java.io.*;
     import java.util.*;

     class IoRedirect {
         public static void main(String Argv[]) {
             try {
                 String[] command = {"/bin/sh", "-c", "/bin/ls > out.dat"};
                 Process p = Runtime.getRuntime().exec(command);
                 p.waitFor();
                 System.out.println("return code: " + p.exitValue());
             } catch (IOException e) {
                 System.err.println("IO error: " + e);
             } catch (InterruptedException e1) {
                 System.err.println("Exception: " + e1.getMessage());
             }
         }
     }

5.7 OK, how do I read the input from a command?

As before, adjusted like this:

     BufferedReader pOut
       = new BufferedReader(new InputStreamReader(p.getInputStream()));    
         try {
            String s = pOut.readLine();
            while (s != null) {
                System.out.println(s);
                s = pOut.readLine();
            } 
         } catch (IOException e) {
         }

5.8 Is it possible to lock a file using Java ?

Java does not feature an API to lock a file or regions within a file. Code that needs to do this must take one of three approaches: 1. implement an advisory locking scheme using features that Java does have (synchronized methods). This allows you to lock files against use by other Java code running in the same JVM. 2. Use an atomic operation like "file delete" and have all processes (Java and non-Java) follow the same protocol: if the file was deleted by you, you have the lock, and you create the file again to give up the lock. 3. make calls to native code to issue the locking ioctls. This approach is not portable, but gives you a shot at having your locks respected by other programs using standard locking ioctls outside Java.

5.9 How do I make the keyboard beep in Java?

In JDK 1.1, java.awt.Toolkit has the method beep(). It does not work on NT 4.0 (bug).

5.10 How do I read a String/int/boolean/etc from the keyboard?

In JDK 1.0.2

     java.io.DataInputStream in = new java.io.DataInputStream(System.in);
     String s = in.readLine();
One way in JDK 1.1
     java.io.InputStreamReader in = new java.io.InputStreamReader(System.in);
     String s = in.readLine();
Once you have the token in a String, it is easy to parse it into one of the other types, as shown earlier in the FAQ.

5.11 How do I compile code which has a cyclic dependency, i.e. class pkg1.X contains a reference to class pkg2.Y ?

You throw both classes at the compiler at the same time.

    javac pkg1/X.java   pkg2.Y.java

5.12 Why do I get a "Statement not reached" error from javac for no apparent reason?

JDK1.0 has a limit of 63 words of storage for local variables in any method. longs and doubles require two words of storage, and all other primitive types and all reference types require one word. If you assign values to more than 63 words of local variables, you will get a "Statement not reached" error on the statement after you assign to the variable that contains the 64th word. In JDK 1.1, the low limit was removed.

5.13 How can I store the errors from the javac compiler in a DOS file? javac > errorfile seems not to work.

Use the following command (documented in the online tools doc for Solaris, but also works in Win32 systems):

     javac -J-Djava.pipe.output=true source.java > errorfile


6. MULTI-MEDIA

6.1 Why won't my audio file play?

Java 1.1 and earlier releases use one audio format exclusively. The audio file must be in .au format, recorded at 8 KHz, mono, in mu-law encoding. If your audio clip is in a different format (e.g., .wav) or a different frequency it must be converted to the exact specifications above before Java can play it.

Search at www.yahoo.com for GoldWave for Win 95, sox for Unix and similar conversion utilities for other systems. One conversion utility in Java is at http://saturn.math.uaa.alaska.edu/~hursha

6.2 Does Java support Animated GIFs?

Java 1.0.2 and earlier releases use GIF and JPEG formats, and do not use the GIF89 animated GIF format. (An animated GIF is one that contains successive frames of an image, so when they are displayed in quick sequence the image appears to contain movement). When you display an animated GIF in Java 1.0.2, you will just get the first frame. You can use cliprect() with a negative x coordinate to get other frames from the image.

The advantage of an animated GIF file is that there is only one file to download, and it is simple to do simple animations. The advantage of programmatic control over individual frames is that you control the rate and order of displaying them.

Here's a surprise: JDK 1.1 supports the animated display of animated GIFs. For simple animations animated GIFs are a lot easier and lighter-weight than coding an animation explicitly.

6.3 How do I play video in Java?

Use the Java Media Framework Player API

The spec can be found at http://www.javasoft.com/products/java-media/mediaplayer/

Intel has released a SDK for the Java Media Framework Player API. The SDK is for Windows 95 and Windows NT For more information, see http://developer.intel.com/ial/jmedia

SGI has released an implementation of JMF for IRIX: See http://www.sgi.com/Products/motion/


7. SECURITY

7.1 What is a "trusted applet"?

JDK 1.1 introduced the notion of a "trusted applet" which is one that has been cryptographically-signed to guarantee its origin and make it tamper resistant. Trusted applets can be granted more system access privileges than untrusted applets.

7.2 What is the story with Java and viruses? What is the blackwidow virus?

Java was designed with security in mind. The security features make it very difficult, probably impossible, to attach a virus (self- copying code) to a Java applet. As far as is known, there has never been a Java virus.

There has been mention of a "Java virus" called "BlackWidow" in the media (it was mentioned in Unigram in late 1996, and obliquely on the RISKS newsletter in February 1997). A request to the editor of Unigram for more information brought the answer that there was no more information, it was just a report of a rumor. As far as is known, this story exists only as rumors reported on by the press. There is no actual Java virus or blackwidow virus (there are legitimate commercial products of that name). If anyone has more concrete information about a virus that can attack a Java applet (again, this is thought to be impossible), please could they contact the FAQ maintainer with details.

7.3 Why do I get the warning string at the bottom of popup windows "Unsigned Java Applet Window" in my applets?

This is a security feature, to make certain that users can always tell that a window asking for their password and credit card details (or whatever) is from an applet. There should be no way to work around this message.

7.4 Where can I find crypto libraries for Java?

Cryptographic libraries are not part of the Java release because US Government policy classifies strong cryptography under the same rules as munitions. Its export is regulated under the International Traffic in Arms Regulations. Many people regard this as a Kafka-esque (and futile) attempt to stem the use of cryptography inside the US.

Please look for the complete crypto API for Java (with HTML documentation) at: http://www.geocities.com/SiliconValley/Heights/8298

The library provides comprehensive and complete range of crypto library and functions covering DES, 3DES, IDEA, Blowfish ...and RSA, DH, DSA and PGP key ring access to Java programmers. The crypto functions are based on cryptlib, written by Peter Gutmann. It would be illegal to export this under current US government rules, but the author of the code is outside the US, and not subject to US export regulations. Download it today before it becomes illegal. Read Bruce Schneier's book Applied Cryptography for more info.


8. FURTHER RESOURCES

8.1 Useful URLS

Latest copy of this FAQ: http://www.best.com/~pvdl/

Other Java resources:

Java Book lists: Javasoft site: http://java.sun.com

Policy on book references: if you have written a book that you think answers one of these FAQ questions especially well, please send me a note of the book, and what your answer is. If I agree it adds value I'll add a reference to your book in the FAQ section.

8.2 Newgroups

These are the Java newsgroups since the reorganization of April 10 1997
  comp.lang.java.help            simple programming and setup questions
  comp.lang.java.announce        (moderated) announcements
  comp.lang.java.advocacy        arguments, yes it is/no it isn't.
  comp.lang.java.programmer      programming in Java
  comp.lang.java.security        security issues
  comp.lang.java.machine         JVM and native interfaces
  comp.lang.java.databases       JDBC,ODBC, java access to DBs.
  comp.lang.java.softwaretools   IDES, editors, compilers, tools, etc
  comp.lang.java.gui             AWT, IFC, JFC, AFC, Vibe, etc etc
  comp.lang.java.beans           Software components in Java


Acknowledgements

Original FAQ copyright February 1997 Peter van der Linden

Contributions from: Matt Kennel, Patric Jonsson, Brad Van Tighem, Tony Hursh Glenn L Vanderburg, Peter Jones, John McDowall, Jim Driscoll, Uday, Dave Harris, Bill Wilkinson, Tom Valesky, Dan Drake, Giles Thomas, Mitch Baltuch, Guy Ruth Hammond, Gordon Keith, Jason Brome, Shani Kerr Steve Chapel, Timothy Wolters, Robert Lynch, Jake Cormier, Sean C Sullivan, Joseph A. Millar, Jim Frost, Jim Balter

[<your name here>: send in a suggested FAQ with the answer]


I am maintaining a FAQ list to address specifically programming issues (not a general tutorial on Java). Please feel free to mail me entries for it. Question with answer gets you a credit in the FAQ. I can be emailed at: linden@sun.com or pvdl@best.com

-- end --