version: comp.lang.java.programmer FAQ list May 2 1997,  Peter van der Linden.

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

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

-------------------------------------------------------------------------
1. LOOKING FOR INFORMATION

1.1 What is the best way to refer someone to the FAQ when they ask a question
    I know is answered there?

A.  The Java Programmers FAQ <http://www.best.com/~pvdl> gives the answer to 
    your question in section N.n.
	...

    This gives them the answer, and shows them where to go for future 
    questions (it also demonstrates that the FAQ can answer their 
    questions, providing an incentive to go there next time.)


1.2 I don't know yet if I want to learn Java.  Is there one book that 
    gives a clear, simple summary of Java and all related technologies,
    without trying to teach me a programming language?

A.  The book "Not Just Java" is the only book currently available
    that contains the overview and explanation you want.  It was written by
    the maintainer of this FAQ, and details are at 
            http://www.best.com/~pvdl

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

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

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

A.  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://sunsite.unc.edu/java/cgi-bin/query
    and look at http://asknpac.npac.syr.edu/    for Java newsgroup search

    http://www.javaworld.com/search.html    can search the Javaworld newspaper

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

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

    Note that only bugs that Sun deems "important" are listed there.
    The criteria for "important" is not published.

    After you have checked whether the bug is already listed, you can
    submit a bug report through:
        http://www.javasoft.com:80/cgi-bin/bugreport.cgi

    You can even send in an RFE or ease-of-use issue there!

    If you go to the JDC (that's the Java Developer's Connection) you can
    do a keyword search against the internal Javasoft bugtraq database,
    looking by keyword or bug number.   JDC has free registration.
    http://developer.javasoft.com  should do it.



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

A.  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.    Try these URLs:
         http://www.ist.co.uk   (search for X-Designer 4.6: Java edition).
         http://members.aol.com/laffra/c2j.html
         http://www.ilog.com/
         http://www.cs.wustl.edu/~schmidt/java_notes.html

    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.
        - j2c from Japan, 
          http://www.webcity.co.jp/info/andoh/java/j2c.html
        - Toba from the Sumatra research project, 
          http://www.cs.arizona.edu/sumatra/toba
        - JCC from Nik Shaylor. 
          http://www.digiserve.com/nshaylor/jcc.html
    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

    This program dumps info about the class file:
    http://www.professionals.com/~cmcmanis/java/dump/index.html
    Chuck McManis was one of Sun's original Java whackers.

1.7 Is there a Java port to Windows 3.1?

A.  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.8 I see a lot of postings from magazines soliciting Java articles.
    Are these legitimate?

A.  Anyone considering writing for the "Java Developer's Journal", or
    any Sys-Con publication, should be aware that there have been 
    several instances of programmers complaining that JDJ has not paid
    them for commissioned articles.  
    
    Another programmer reported that he was not paid by Sys-Con for an
    article for their Delphi magazine.   There is a pattern of programmers
    complaining that SYS-CON has not paid them.   
    Programmer beware, and please don't support magazines that cheat 
    their programmer contributors.
    
1.9  What are the good folks at project Gnu doing with Java?

A.  Guava (the Gnu Java compiler) can be found at 
         http://http.cs.berkeley.edu/~engberg/guavac/
    Kaffe (a JVM) can be found at 
         http://www.kaffe.org


-------------------------------------------------------------------------
2. COMPILERS, ETC.

2.1  Why did I get an OutOfMemory error when porting working code 
    from jdk 1.02 -> 1.1

A.  The preset memory limit seems to have changed.  It went to 16Mb
    You can adjust it with 
            java -mx32m  Frotz

    Also see the Runtime methods freeMemory() and totalMemory().
    [Can anyone state with evidence what the 1.0.2 limit was?]

2.2  Is there a lex and yacc or preferably a flex and bison equivalent
     for Java?

A.   There is a lex equivalent called JavaLex and a yacc equivalent called
     CUP.

    LR(1) parser
	JavaLex and JavaCup: http://www.cs.princeton.edu/~appel/modern/java/
    
    LL(k) parser
	JavaCC: http://www.suntest.com/Jack/

2.3  Where can I find a byte code obfuscator?

A.       HashJava: http://www.blackdown.org/~kbs/hashjava.html


-------------------------------------------------------------------------
3. LANGUAGE ISSUES
3.1 Why doesn't my "hello world" program work?

A.  Two very common causes of failure are:
    * the class name and the file name must match exactly, even letter case.
      If your class is HelloWorld, your source file must be HelloWorld.java
    * the $CLASSPATH environment variable should include "." (current dir).

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

A.  Of all the misconceptions about Java, this is the most egregious.  
    Far from not having pointers, in Java, object-oriented programming is
    conducted exclusively with pointers.  In other words, objects are
    only ever accessed through pointers, never directly.  The pointers are
    termed "references" and they are automatically dereferenced for you.

    Java 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?


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

A.  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" as described in the
    previous answer.

    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.

3.4  How, then, can I pass an object to a method, and have the method change
     the reference so it points to a different object?

A.  There are two ways.  The obvious way is "just add another level of
    indirection" -- wrap the object in another class, whose purpose is simply
    to be passed as a parameter, allowing the nested object reference to be
    modified.

    The second alternative is a clearer variant of this.  Pass in a single 
    element array.  Since arrays are objects, this works.
           void jfoo(Object ref[]){
                ref[0] = new Object();
            }

3.5 Why is String a final class?  I often want to override it in some way.

A.  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.

3.6 How are finalizers different from C++ destructors?

A. 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 of 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.

3.7 What happened to "private protected"?

A. 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.

3.8 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 (i.e. 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 (i.e. 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.

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

A. 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.

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

A.  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.


3.11 Why do I get the 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);
     }

A.  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.

3.12 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.

A.  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.

3.13 Why do I get this compiler error message?

    myApplet.java:11: No constructor matching myCheckbox(myApplet)
    found in class myCheckbox.

            bp1 = new myCheckbox(this);
                      ^
            1 error

A.  The first thing to check is whether you gave a return value to the
    constructor, like this:
           public void myCheckbox( Container parent )

    If you did, the compiler will think it is an ordinary method, not a
    constructor.  This is a very common mistake, and quite hard to spot.

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

A.  char c = 'A';
    int i = c;

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

    This question crops up so frequently because the BASIC language
    uses functions to map characters into ints,   ASC( 'A' )  => 65
    causing BASIC programmers to seek the corresponding Java functions.

-------------------------------------------------------------------------
4. APPLETS and AWT

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

A.  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:
  - Make sure you transfer the class files in binary mode, rather than
    text or ASCII mode.
  - Make sure you transfer *all* of the class files which are a part
    of your applet.  Sometimes people are surprised by how many there
    are.  There will be a class file for every class and interface you
    define, even if you define more than one in a single source file.
    If you use the Java 1.1 "inner classes" feature, there will be class
    files for each inner class as well.
  - Make sure you maintain the appropriate case distinctions in your
    filenames.  If a class is called StUdLy, it must be found in a
    file called StUdLy.class.
  - Make sure you maintain the directory structure that matches your
    package structure.  If you declare a class in package
    COM.foo.util, the class file needs to be in directory COM/foo/util
    under the applet's codebase directory.  Again, case distinctions
    are important for package/directory names, just as they are for
    class/file names.
  - Make sure that the web server process will have read access to the
    class files, and search access to the directories that the files
    are in.  For example, if the web server runs on a Unix machine, use
    the command "chmod o+r filename" for the files, and
    "chmod o+x dirname" for the directories.

4.2 Why do I get this when using JDK 1.1 under X Windows?
     java.lang.NullPointerException
         at sun.awt.motif.MFramePeer.<init>(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)

A.  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.


4.3 how do you make the applet's background transparent?

A.  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.

    Lightweight components (new in JDK 1.1) have a transparent background.

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

A.  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.
    4. Use a trusted applet (see section on security).  This will 
       permit local I/O.
    5. Or use a browser that has a security policy that is configured to
       allow file I/O (such as Sun's appletviewer).

4.5 Why is GridBagLayout so hard to use?

A.  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.

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

A.  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 
       additive combination (e.g. Font.ITALIC+Font.BOLD).
       FONTSIZE is the size of the font, e.g. 12.

4.7  MyClass works fine except when I try to set a particular font.
     I just can't seem to get it to work in Win95, but I can get it to
     work on a MacOS and Unix.

A.  You probably specified a font name that isn't available under 
    your Win95; this is one of those cross-platform incompatabilities
    that come back to bite people, like specifying 'Arial' as a font and
    expecting it to work on something other than Windows, or using
    (e.g.) 'Helvetica' and expecting it to be there.  As an experiment,
    write a short app that enumerates the available fonts -- it'll probably
    be quite different from what you expect.

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

A.  Toolkit.getDefaultToolkit().getScreenSize()

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

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

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

A.  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.

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

A.  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.

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

A.  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."

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

A.  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 you can use CardLayoutManager.

-------------------------------------------------------------------------
5. CORE LIBRARIES
5.1 I can't seem to change the value of an Integer object once created.

A.  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; }

5.2 How do I print from a Java program?

A.  Use the Toolkit.getPrintJob() method
      
      Component c = this.getParent();
      while (c!=null && !(c instanceof Frame)) c=c.getParent();

      PrintJob pj = getToolkit().getPrintJob((Frame) c, "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.
    Printing from an untrusted applet is subject to a check from the 
    SecurityManager. 

5.3 Is there any package in Java to handle HTML?

A.  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.

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

A.  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.

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

A.  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.

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

A.  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.


5.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).

A.   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.

   
5.8 How are dates represented in Java?

A.  java.util.Date stores dates as integers representing the number of
    seconds since 00:00:00 UTC Jan 1, 1970 (the birth of Unix, a date 
    known as the "Epoch").  

    Dates earlier than the Epoch are represented as negative numbers, 
    counting away from 1/1/1970.  It is a poorly-conceived representation, 
    spanning just the years 1902-2038, and more classes were added 
    in JDK 1.1.

    Note that this differs from the Java specification which says that
    Dates should be stored as a long, and contain milliseconds since the
    Epoch.  That actually gives a reasonable range (although making dates
    before the Epoch be negative is still suspect).
  
    [Note: seeking contributions from anyone with more comprehensive data].

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

A.  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.

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

A.  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().
    StreamTokenizer does a similar thing on a file (i.e, what scanf() and 
    fscanf() do in C).

5.11 I can't seem to change the current working directory.

A.  Correct.  This missing functionality is an oversight that we hope will
    be corrected in future.    Changing the user.dir property merely changes
    the text property, not the underlying reality that it is supposed to
    reflect.

5.12 How do I create a Vector of ints?

A.  ints are primitive types and hence can't be stored by the Vector class
    which stores objects. You'll need to wrap the ints. Try this:

	int i =7;
	Vector holdsInts = new Vector(5,1);

	holdsInts.addElement(new Integer(i));
	int j = ((Integer)holdsInts.elementAt(0)).intValue();


-------------------------------------------------------------------------
6. NETWORKING & DISTRIBUTED OBJECTS
6.1 Should I use CORBA in preference to RMI?  Or what?

A.  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 C++ (or other language) systems or you 
    need CORBA-specific services, then CORBA is your choice.

6.2 Why does <my java debugger/IDE/other> hang for a couple of minutes
    if if my Windows PC is not dialled up to the Internet?

A.  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!]

6.3 If I call the InetAddress.getByName() method with an IP-address-string
    argument, like "192.168.0.1", I get an unknowHostException on some
    platforms, but not others.  Code like
         Socket sock = new Socket("155.152.5.1", 23);
    triggers the exception.  Why?

A.  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?]


6.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

A.  It sounds like your java\bin directory is not on your PATH and 
    so the system can't find the winawt DLL.  
    But specifically, the problem is that Sun linked the winawt_g.dll
    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.

6.5 I want to pass a class file to willing recipients who are using
    my applet.   Any ideas how?

A.  You could use a trick: put your .class file(s) in a .zip archive and use
    showDocument() on the URL.  A person accessing this will get a dialog
    box put up asking them about saving the file to their local hard disk. 
    You can see this in action and try it out yourself at:
           http://www.best.com/~rmlynch/saveit.html

6.6 How do you succeed with new URL(someURL) from behind a proxy server? 

A.  Tell the run time system what you are trying to do, like this:
    java -DproxySet=true -DproxyHost=proxy_host -DproxyPort=proxy_port \
                        MyJavaProgram
    note proxyPort is optional and it defaults to 80.

-------------------------------------------------------------------------
7. Java IDIOMS
7.1 How do I convert a String to an int?

A.  There are several ways.   The most straightforward is:
       int i = Integer.parseInt(<String>);
    or i = Integer.parseInt(<String>,<int radix>);

    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.

7.2 How do I convert an int to a string?

A.    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.

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

A.  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

7.4 How do I append to a file?

A.  First, do this:
        RandomAccessFile fd = new RandomAccessFile(file,"rw");
        fd.seek(fd.length());
    Then write using fd.

7.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.

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

A.  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());
             }
         }
     }


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

A.  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) {
        }


7.8  Is it possible to lock a file using Java ?

A.   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.  

7.9  How do I make the keyboard beep in Java?

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

7.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.BufferedReader in = 
          new java.io.BufferedReader( new 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.
     Yes, it is bone-headed, as it makes the simplest case of keyboard I/O
     unnecessarily complicated.

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

A.    You throw both classes at the compiler at the same time.
           javac pkg1/X.java   pkg2.Y.java


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

A.  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.

7.13  How can I store the errors from the javac compiler in a DOS file?
      javac > errorfile seems not to work
 
A.  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


7.14 How can I pretty-print Java source?

A.  Some Unix utilities work adequately:
     indent (fails with "//" comments though)
     cb (very few style choices though)

     alias printjava 'vgrind -lC++ -t -w \!* | lp'    
         works pretty well too.

   
-------------------------------------------------------------------------
8. MULTI-MEDIA
8.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

8.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.

8.3 How do I play video in Java?

A.  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/

8.4 How can I play *.au files from an application?

A. You've got 2 options:

   a.  Use the AudioClip class in sun.audio
       http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
       If you take this option, you can only play AU files.

   b.  Use the new Java Media Framework API, allowing a wide range of
       video and audio formats to be played back.
       See previous question for implementations of this.

8.5 How do I read in an image file, in an application?

A.   Use
        Image img = Toolkit.getDefaultToolkit().getImage(fname);

-------------------------------------------------------------------------
9. SECURITY

9.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.


9.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.

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

A.  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.

9.4  Where can I find crypto libraries for Java?

A.  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.
    
    A comprehensive and free crypto library (called Cryptix) is at
             http://www.systemics.com/software

    One commercial Java encryption source (from Ireland) is
             http://www.baltimore.ie/jcrypto.htm

    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.

9.5  How do I find out what these terms mean?

A.  Read Bruce Schneier's excellent book "Applied Cryptography 2nd Ed." for
    more info on what these terms mean.
    Read David Kahn's excellent (if exhaustive) book "The Codebreakers" for
    more info on the history and background of encryption.
   
-------------------------------------------------------------------------
10. FURTHER RESOURCES

10.1 Useful URLS

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

    Other Java resources:
       Much Java information     http://www.gamelan.com
       The Java "Hall" of Fame:  http://www.apl.jhu.edu/~hall/java/
       good glossary: http://oberon.ark.com/~roedy
       conversions:   http://oberon.ark.com/~roedy/convert.htm
       good JDBC FAQ:  http://www.yoyoweb.com/Javanese/JDBC/FAQ.html
       alternative FAQ (obsolete/inaccurate/shaky in parts) 
                             http://sunsite.unc.edu/javafaq/javafaq.html
       tutorial:  
              http://www.javasoft.com:80/nav/read/Tutorial/index.html
              http://www.phrantic.com/scoop/onjava.html

    Java Book lists: 
              http://lightyear.ncsa.uiuc.edu/~srp/java/javabooks.html
              http://www.netcharts.com/majug/reviews.html
              http://www.avena.net/~dong/book.htm
              http://wwwiz.com/books

    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.
    
10.2 Newgroups
    These are the Java newsgroups since my reorganization of April 10 1997

      comp.lang.java.help            simple programming and setup questions
      comp.lang.java.announce       (moderated) announcements
      comp.lang.java.advocacy        for arguments: no it isn't, yes it is
      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

    As with the other language groups on Usenet (comp.lang.c, comp.lang.c++, etc)
    questions about products from specific vendors that only work on one specific
    vendors platforms are best posted to other newsgroups.  For example, questions
    about ActiveX belong in comp.os.ms-windows.programmer.ole, not the Java groups.
    Or try the group microsoft.public.java.visualj++.  This is available from
    Microsoft's news server msnews.microsoft.com .


-------------------------------------------------------------------------

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, Jeff Bauer, John Kochmar, Carl Burke
William Stubbs

[<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 -- 
