home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / computer-lang / java / programmers / faq
Encoding:
Internet Message Format  |  1999-05-22  |  412.4 KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!news.kodak.com!news-nysernet-16.sprintlink.net!news-east1.sprintlink.net!news-peer1.sprintlink.net!news.sprintlink.net!newsfeed.berkeley.edu!news2.best.com!news3.best.com!nntp1.ba.best.com!not-for-mail
  2. From: pvdl@best.com (Peter van der Linden)
  3. Newsgroups: comp.lang.java.programmer,comp.lang.java.help,comp.lang.java.gui,comp.answers,news.answers
  4. Subject: Java Programmers FAQ
  5. Supersedes: <7ha5k9$3ng$1@shell15.ba.best.com>
  6. Followup-To: poster
  7. Date: 21 May 1999 13:50:56 -0700
  8. Approved: news-answers-request@MIT.EDU
  9. Message-ID: <7i4gvg$1aq$1@shell15.ba.best.com>
  10. Summary: This posting answers frequently-asked questions by Java programmers
  11. Lines: 9607
  12. NNTP-Posting-Host: shell15.ba.best.com
  13. X-Trace: nntp1.ba.best.com 927319862 226 pvdl@206.184.139.147
  14. Xref: senator-bedfellow.mit.edu comp.lang.java.programmer:210403 comp.lang.java.help:54566 comp.lang.java.gui:33281 comp.answers:36236 news.answers:158373
  15.  
  16. Archive-name: computer-lang/java/programmers/faq
  17. Posting-Frequency: weekly
  18. Last-modified: 1999/05/19
  19. URL: http://www.afu.com/javafaq.html
  20.  
  21. Frequently Asked Questions (with answers) for Java programmers
  22.  
  23.            _____________________________________________________
  24.   ________|                                                     |________
  25.   \       |   Java Programmers FAQ         http://www.afu.com   |       /
  26.    \      |   Last modified May 19, 1999   Peter van der Linden |      /
  27.    /      |_____________________________________________________|      \
  28.   /___________)                                              (__________\
  29.  
  30. The Java FAQs here are intended for people who already have some programming
  31. experience, though maybe not in Java.
  32.  
  33. Go to the FAQ home page at http://www.afu.com for other Java information and
  34. downloads, and the most up-to-date copy of the FAQ. Report FAQ updates to
  35. faqidea at the address afu.com.
  36.  
  37. ------------------------------------------------------------------------
  38.  
  39. The sections of the Java FAQ are:
  40.  
  41.    * 1. Java Book Information
  42.    * 2. Getting Started
  43.    * 2.5 Portability
  44.    * 3. General Information
  45.    * 4. Compilers and Tools
  46.    * 5. Compiler Messages
  47.    * 6. Java Language issues
  48.    * 7. I/O
  49.    * 8. Core library issues
  50.    * 9. Computer Dating
  51.    * 10. AWT
  52.    * 11. Swing
  53.    * 12. Browsers
  54.    * 13. Applets
  55.    * 14. Multi-Media
  56.    * 15. Networking
  57.    * 16. Security
  58.    * 17. For C, C++ Afficionados
  59.    * 18. Java Idioms
  60.    * 19. Java Gotcha's
  61.    * 20. Further Resources
  62.    * 21. Acknowledgements
  63.  
  64.                        -------------------------------
  65.  
  66. 1. Java Book Information
  67.  
  68.   1. (sect. 1) How do I choose a Java book?
  69.  
  70.      [*] There is no one right answer to "which is the right Java book for
  71.      me?"
  72.      A lot depends on what you already know, and how you like to
  73.      learn.
  74.      If you already know how to program in another language, and Just want
  75.      to learn Java, consider Just Java 1.2 from the FAQ author.
  76.  
  77.      Everything in one handy volume (language basics, Swing, networking,
  78.      I/O, database access, etc) and it comes with a CD with tons of Java
  79.      applets, games, applications, compiler tools, complete with source.
  80.      Includes a Java compiler for Windows, the Mac, Linux, and Solaris
  81.      (sparc and x86). look at http://www.amazon.com for details
  82.  
  83.       If you or your manager instead want a briefing on Java
  84.       technology, thin clients, XML, CORBA, TCP/IP, Java beans,
  85.       etc., take a look at Not Just Java from the FAQ author.
  86.                                                                     [Image]
  87.       This book doesn't teach you how to program in Java; it tells
  88.       you why you might want to, and what kind of systems are most
  89.       suited to Java. It describes E-Commerce and XML. look at
  90.       http://www.amazon.com for details
  91.  
  92.      Here are the points to check when evaluating a programming book.
  93.         o Above all, make sure that it is a Java book. If it comes with a
  94.           CD, check that it has a Java compiler on it, not a J++ compiler.
  95.           VJ++ does not implement Java 2. VJ++ is also a different language
  96.           in some important ways, and is missing the latest Java libraries
  97.           (Swing, Collections, JFC, RMI). If your interest is Java, leave
  98.           the downrev VJ++ book back on the shelf.
  99.         o Does the book cover the current level of Java, which is Java 1.2
  100.           (aka Java 2)? Look up "JApplet" in the index. If it's not there
  101.           the book doesn't cover JDK 1.2, and you probably need a more
  102.           up-to-date book.
  103.         o Check that the book has a reasonable number of figures, diagrams,
  104.           and illustrations. It is not possible to explain how to program a
  105.           window system without pictures and diagrams. Other topics benefit
  106.           from pictures, too.
  107.         o Check what the book says about itself. Is it a reference work,
  108.           intended for Java-experts to look things up in? This is the role
  109.           of "Java in a Nutshell", and "The Java Almanac". Do you need that,
  110.           or are you looking for a book that teaches by examples and
  111.           explanations?
  112.         o Read Peter Norvig's excellent advice on learning programming
  113.           languages and being a programmer.
  114.         o Appraise your own level of programming knowledge: are you
  115.           proficient in some other language, or are you learning programming
  116.           as well? Does the book cater to your level?
  117.         o Read a section of the book. Does the style keep you interested, as
  118.           it educates you? Will you get bored if you read many pages? Is the
  119.           book too long for your initial purpose? Browse Amazon online and
  120.           see what other readers say about the text.
  121.         o If the book comes with a CD, how much other software is on the CD?
  122.           You want at least a Java compiler plus all the examples from the
  123.           book. Does the Java compiler work on your platform (Mac, Linux,
  124.           etc)? Additional software on the CD is a big plus, as we learn the
  125.           most from reading other people's code.
  126.  
  127.      Most people buy one book to begin with, then four or five more as they
  128.      wish to learn more, and about more specialized topics. The FAQ author
  129.      has purchased and read probably 60 Java books in the last three years.
  130.  
  131.   2. (sect. 1) Where can I find a some lists of Java books and book reviews?
  132.  
  133.      [*] Here are some good ones:
  134.      http://www.hszk.bme.hu/~werner/Java2BookReviewBETA.html
  135.      and
  136.      http://www.geocities.com/RainForest/Canopy/4774/Java/education.html
  137.      also
  138.      http://www.flathill.com/languages/java/
  139.      also
  140.      http://www.fastgraph.com/books/java.html
  141.      also
  142.      http://teamjava.com/links/tj-srv.cgi?MUF=0,tj-booklist.muf
  143.      also
  144.      http://www.javaworld.com/javaworld/books/jw-books-index.html
  145.      (an exhaustive list -- takes a long time to load).
  146.  
  147.                        -------------------------------
  148.  
  149. 2. Getting Started
  150.  
  151.   1. (Sect. 2) What is the easiest way to get started with Java?
  152.  
  153.      [*] Follow these steps.
  154.        1. Look at the books section of the FAQ to see what kind of book will
  155.           suit you. There is no one perfect Java book. The right book
  156.           depends on the style, pace, and detail that you are comfortable
  157.           with. Amazon has good info and reviews on Java books.
  158.  
  159.        2. Download a free Java compiler from http://java.sun.com Service
  160.           packs for Solaris (if any are needed) can be found at:
  161.           http://www.sun.com/solaris/jdk/download.1.2.1_02/en/sparc/1.2.1_02_sparc_jdk_patches.tar
  162.  
  163.        3. Read the free Java tutorial, at
  164.           http://java.sun.com/docs/books/tutorial/index.html
  165.           (bookmark it, so you will easily find it again).
  166.  
  167.        4. Avoid Microsoft's J++ product, which is in the words of
  168.           Microsoft's own employees "polluted Java". It is designed to
  169.           undermine standard Java, and has many deliberate platform-specific
  170.           incompatibilities, including new keywords in the language.
  171.  
  172.        5. To get some tips on getting started with a programming homework
  173.           assignment, look at http://www.concentric.net/~pats/beginner.html.
  174.  
  175.        6. Search this FAQ when something in Java confuses you. Many people
  176.           have trodden this path before you, and the FAQ contains the
  177.           accumulated knowledge and pointers to other references.
  178.  
  179.   2. (Sect. 2) Why doesn't my "Hello World!" program compile?
  180.  
  181.      [*] There are three basic possibilities:
  182.        1. Are you successfully running the javac compiler?
  183.           Try
  184.  
  185.           javac -garbage
  186.  
  187.           to see if it prints out a message about correct usage. If not,
  188.           invoke javac using the full pathname, or set your PATH variable to
  189.           include the directory that contains javac.
  190.        2. Is the CLASSPATH environment variable used correctly?
  191.           In JDK 1.0.2, beginners had to set CLASSPATH, and it had to
  192.           include both system libraries and your programs.
  193.           In JDK 1.2, CLASSPATH is no longer needed for system libraries.
  194.           You do want CLASSPATH to point to the directories containing any
  195.           "user classes" you're using.
  196.           Getting started, you will probably want at a minimum "." (the
  197.           current directory) in your CLASSPATH.
  198.           When CLASSPATH is wrong, javac will tell you it can't find
  199.           definitions for classes you reference in the source file. For
  200.           information on setting up the CLASSPATH, see Question 1.3
  201.        3. Is the source correct?
  202.           Here javac will emit error and warning messages. See the questions
  203.           on compiler messages in the next section.
  204.  
  205.   3. (Sect. 2) Why doesn't my "Hello World!" program run?
  206.  
  207.      [*] There are five common mistakes that cause your VM (java or browser)
  208.      to be unable to execute your classes
  209.        1. First, did you write an applet or an application? If an applet,
  210.           you must make sure that you did extend the java.applet.Applet
  211.           class. Your starting code should be in the init routine.
  212.           If you wrote an application, your starting code should be in a
  213.           routine called main(). Don't mix applets with applications until
  214.           you have a bit more experience.
  215.        2. You must declare your main class as "public". If you don't,
  216.           unfortunately some systems will still run the code, while others
  217.           won't. The main class is either the one with the main() method in,
  218.           or in the case of an Applet, the class that extends Applet.
  219.        3. Your class name and the file name must match exactly, even letter
  220.           case. If your class is HelloWorld, your source file must be
  221.           HelloWorld.java and your class file will be "HelloWorld.class".
  222.        4. If an Applet, and you used ftp to transfer the classes to the
  223.           server, you must ftp all the classes, and you must use BINARY
  224.           transfer not ASCII.
  225.        5. Errors in setting the CLASSPATH (and/or codebase in an applet).
  226.           Even seasoned programmers do this, pointing inside a package or
  227.           mistyping a path delimiter. For information on setting up the
  228.           CLASSPATH and codebase, see Question 1.3
  229.  
  230.      If you are running an applet, you should check the following further
  231.      points:
  232.        1. If your class isn't loading, recheck the HTML applet tag.
  233.        2. If you are writing to System.out, the results are displayed in the
  234.           browser's java console. You'll have to create a window if you want
  235.           one.
  236.        3. Make sure your browser is compatible with the Java language
  237.           features you are using. Internet Explorer and older versions of
  238.           Netscape's browsers have omitted some support for JDK 1.1. Try
  239.           your applet in the JDK's appletviewer first.
  240.  
  241.   4. How do I set the CLASSPATH?
  242.  
  243.      [*] The CLASSPATH environment variable tells the VM's class loader
  244.      where to find classes that are directly or indirectly invoked,
  245.      including system classes. The CLASSPATH variable should
  246.         o point to the directory containing the class file, for classes not
  247.           in a package.
  248.         o point to the package root, for classes in a package. The root is
  249.           the parent directory of the highest directory of the package name.
  250.         o point directly to the zip or jar file, if the classes are in an
  251.           archive file. You may have to list the contents of the archive to
  252.           get the correct package/path name for the class.
  253.           Separate multiple paths and archives with a platform-specific
  254.           separator, ";" for Windows; ":" for Solaris
  255.      Also remember that
  256.         o Browsers set the CLASSPATH to the directory of the HTML file, plus
  257.           the codebase parameter.
  258.         o in JDK 1.1 and after, java adds the system classes
  259.           (lib/classes.zip), so you don't have to.
  260.         o JDK 1.2 versions of java add "." (current directory), so you don't
  261.           have to. (But jre doesn't - see below.)
  262.         o JDK 1.1 jre tool does not use the CLASSPATH variable or assume the
  263.           current directory. (On Solaris, CLASSPATH does work.)
  264.  
  265.      From JDK 1.1.2 on, it is generally an error if the user sets the
  266.      CLASSPATH to include classes.zip. But CLASSPATH will need to be set to
  267.         o point to the roots of the programmer's own packages, and third
  268.           party packages
  269.         o use rmic
  270.         o use unbundled packages like Swing in JDK 1.1
  271.         o point to native code libraries.
  272.  
  273.      For the sake of consistency, the minimal classpath setting should be: "
  274.      set CLASSPATH=. "
  275.      Below you'll find examples for Windows (basic application class),
  276.      Solaris (package class), javac (multiple packages), and browsers
  277.      (applet codebase).
  278.      -----------------------------
  279.  
  280.      Here's some Windows examples, assuming the application class is
  281.  
  282.      D:\src\tries\HelloWorld.class
  283.  
  284.              ## JDK 1.1,  no CLASSPATH set
  285.              > cd D:\src\tries\
  286.              > D:\jdk11\bin\java HelloWorld
  287.                # OK: 1.1 implicitly adds classes.zip and current dir
  288.  
  289.              > D:\jdk11\bin\jre HelloWorld
  290.                # FAILS: jre does not automatically add . to CLASSPATH
  291.  
  292.              > cd D:\
  293.              > D:\jdk11\bin\jre -cp D:\src\tries HelloWorld
  294.                # OK: jre adds classes.zip, -cp adds class directory
  295.  
  296.              ## JDK 1.1,  CLASSPATH set
  297.              > set CLASSPATH=D:\src\tries
  298.              > D:\jdk11\bin\java HelloWorld
  299.                # OK: java using CLASSPATH
  300.  
  301.              > D:\jdk11\bin\jre HelloWorld
  302.                # FAILS: jre does not use CLASSPATH (on Windows)
  303.  
  304.              ## JDK 1.0.2,  CLASSPATH set
  305.              > set CLASSPATH=D:\jdk102\lib\classes.zip;D:\src\tries
  306.              > D:\jdk102\bin\java HelloWorld
  307.                # OK:
  308.  
  309.              > set CLASSPATH=D:\jdk102\lib\classes.zip;D:\src\tries
  310.              > D:\jdk11\bin\java HelloWorld
  311.                # FAILS: exception in thread NULL - wrong system classes
  312.  
  313.  
  314.      -----------------------------
  315.  
  316.      Here's some Solaris examples, assuming the application class is
  317.  
  318.      /usr/src/com/devjoes/killer/App.class
  319.  
  320.      and it is in package com.devjoes.killer:
  321.  
  322.              # JDK 1.1, no CLASSPATH set
  323.              $ /usr/bin/jdk11/bin/jre  -cp /usr/src   com.devjoes.killer.App
  324.                # OK:
  325.  
  326.              $ cd /usr/src/com/devjoes/killer/
  327.              $ /usr/bin/jdk11/bin/java App
  328.                # fails: class name and path are wrong
  329.  
  330.              $ CLASSPATH=/usr/src/
  331.              $ /usr/bin/jdk11/bin/java App
  332.                # fails: class name is com.devjoes.killer.App
  333.  
  334.              $ /usr/bin/jdk11/bin/java com.devjoes.killer.App
  335.                # OK:
  336.  
  337.  
  338.      -----------------------------
  339.  
  340.      Here's some javac examples, for both Solaris and Windows, based on the
  341.      following:
  342.       Source files                package           Makes the call
  343.       /usr/src/pack/Minimal.java  package pack      pack.sub.Try.run()
  344.       /usr/src/pack/sub/Try.java  package pack.sub  (nothing)
  345.  
  346.              $ CLASSPATH=""
  347.              $ /usr/bin/jdk11/bin/javac /usr/src/pack/sub/Try.java
  348.                # OK: works fine
  349.  
  350.              $ /usr/bin/jdk11/bin/javac /usr/src/pack/Minimal.java
  351.                # FAILS: can't find pack.sub.Try
  352.  
  353.              $ cd /usr/src
  354.              $ /usr/bin/jdk10/bin/javac pack/Minimal.java
  355.                # OK: finds pack.sub.Try based on . as package root
  356.  
  357.              $ cd /usr/src/pack
  358.              $ CLASSPATH=/usr/src
  359.              $ /usr/bin/jdk11/bin/javac Minimal.java
  360.                # OK: finds pack.sub.Try based on CLASSPATH
  361.  
  362.  
  363.      Now assume the killer application class
  364.  
  365.      /usr/src/com/devjoes/killer/FastApp.java
  366.  
  367.      (in package com.devjoes.killer) uses a third-party package in a jar
  368.      file
  369.  
  370.      /usr/jars/JShapes.jar
  371.  
  372.      but makes no other reference to other classes. The following works
  373.      fine:
  374.  
  375.              $ CLASSPATH=/usr/jars/JShapes.jar
  376.              $ cd /usr/src/com/devjoes
  377.              $ /usr/bin/jdk11/bin/javac killer/FastApp.java
  378.  
  379.  
  380.      Finally, some applet examples. Many applets only use one class, in the
  381.      same directory as the html file:
  382.  
  383.      <applet code=ArcTest.class height=400 width=400>
  384.  
  385.  
  386.      To use classes in subdirectory, use the codebase parameter:
  387.  
  388.      <applet codebase="mysubdir/" code=ArcTest.class ..
  389.  
  390.  
  391.      To use classes in an archive, use the archive parameter:
  392.  
  393.      <applet archive="applets.jar" code=ArcTest.class ..
  394.  
  395.  
  396.      See also: JDK 1.1 ReadMe
  397.      Solaris JDK 1.1 tool documentation
  398.      Win32 JDK 1.1 tool documentation
  399.  
  400.   5. (Sect. 2) How do I do keyboard (interactive) I/O in Java?
  401.  
  402.      [*] Interactive I/O in Java is very poorly supported. Programmers must
  403.      piece together several library classes in non-obvious ways to get the
  404.      required functionality. See the answer to Question 7.1.
  405.  
  406.   6. (Sect. 2) How do I do file I/O in an applet?
  407.  
  408.      [*] By default, an applet can read files on the server, but not write
  409.      them, and has no access to the client. This is for reasons of security.
  410.      It would be very unsafe to let any old applet that you downloaded from
  411.      an unknown origin on the Internet read/write your files. It would be as
  412.      unwise as allowing this kind of access to an ActiveX control (which is
  413.      one reason ActiveX is dead on the Internet).
  414.  
  415.      There are several different ways to relax the default rules. See the
  416.      answer to Question 7.8.
  417.  
  418.   7. (Sect. 2) How do I do I/O to the serial port on my computer?
  419.  
  420.      [*] Java 1.0 and 1.1 do not have a serial port API. There are several
  421.      commercially-available libraries that supply the needed functionality.
  422.      JDK 1.2 introduces access to the serial and parallel ports as an
  423.      extension (optional extra) library. See also the answer to Question
  424.      6.3.
  425.  
  426.   8. (Sect. 2) How do I do formatted I/O like printf and scanf in C/C++?
  427.  
  428.      [*] The java.text package introduced with Java 1.1 supports formatted
  429.      I/O. See also the answer to questions 7.11, 7.12, and 17.7.
  430.  
  431.   9. (Sect. 2) I have spent more debugging time finding case (upper vs
  432.      lower) typos than everything else put together and squared!
  433.  
  434.      [*] Do not forget that your remark must be phrased in the form of a
  435.      question to win on FAQ Jeopardy. In any event, it is worth reminding
  436.      those new to Java that letter case really matters in Java, and that the
  437.      names of public classes should exactly match (including case) the names
  438.      of the files they live in. See also the answer to Question 1.1.2
  439.  
  440.  10. (Sect. 2) Why do I get this compiler error: "Can't make static
  441.      reference to method..."?
  442.  
  443.      [*] Your code probably looks something like this:
  444.  
  445.      class myclass {
  446.                  public static void main(String args[]) {
  447.                      myMethod();
  448.                  }
  449.  
  450.                  public void myMethod() {
  451.                      //some code
  452.                  }
  453.              }
  454.  
  455.  
  456.      The issue is this: a static method means it belongs to the class, not
  457.      each individual object. If you leave the static keyword off (the usual
  458.      case) as is done here with the method "myMethod()", it means that
  459.      method can only be invoked on an object. But your call from main() has
  460.      not told myMethod() which object it is to be invoked on. Inside a
  461.      non-static method, you don't have to provide this information, as it
  462.      assumes you mean the same object on which it was invoked. But when
  463.      calling from a static method, you must provide the information, and you
  464.      haven't - hence the error message.
  465.  
  466.      A common fix is to instantiate a member of the class, on which to
  467.      invoke myMethod(), like this:
  468.  
  469.              public static void main(String args[]) {
  470.                  myclass m = new myclass();
  471.                  m.myMethod();
  472.              }
  473.  
  474.  
  475.      This problem is especially common when you are writing code that you
  476.      want to run as an applet and as an application. Naturally, you call
  477.      init() and start() from main. What you really need to do is:
  478.  
  479.              public static void main(String[] args) {
  480.                  Applet ma = new myApplet();
  481.                  ma.init();
  482.                  ma.start();
  483.              }
  484.  
  485.  
  486.  11. (Sect. 2) Why can't I do myArray.length() ? Arrays are just objects,
  487.      right?
  488.  
  489.      [*] Yes, the Java specification says that arrays are object references
  490.      [JLS 10.2] just like classes are. However, arrays cannot contain
  491.      methods. Instead you have to use myArray.length, which is a data item
  492.      (not a method) called "length", belonging to myArray.
  493.  
  494.  12. (Sect. 2) How do I close a Java window by using the icon in the upper
  495.      right hand corner of a window?
  496.  
  497.      [*] Create an event handler class to extend WindowAdapter. Then
  498.      override WindowAdapter's windowClosing() to do the actions you want
  499.      when a window's "close" action is clicked. Then add that to the
  500.      listeners for that window.
  501.  
  502.      import java.awt.*;
  503.      import java.awt.event.*;
  504.  
  505.      public class MyFrame extends Frame {
  506.          public MyFrame(String s) {super(s);}
  507.  
  508.          public class WL extends WindowAdapter {
  509.              public void windowClosing(WindowEvent e) {System.exit(0);}
  510.          }
  511.  
  512.          // do your other Frame stuff
  513.  
  514.      }
  515.  
  516.  
  517.      Somewhere in your initialization code, put:
  518.  
  519.              f1.addWindowListener( f1. new WL()  );
  520.  
  521.  
  522.      This last syntax is not commonly known to many people yet, it's another
  523.      wacky artifact of inner classes.
  524.  
  525.      Alternatively, combining the inner class and setting the handler in one
  526.      go, you could do this:
  527.  
  528.              MyFrame f1 = new f("wave");
  529.  
  530.              f1.addWindowListener( new WindowAdapter() {
  531.                  public void windowClosing(WindowEvent e) {
  532.                      // and/or setVisible(false) and/or dispose()
  533.                      System.exit(0); }
  534.              });
  535.  
  536.  
  537.      See also the answer to questions 1.0.19, 1.0.30 and 15.7.
  538.  
  539.  13. (Sect. 2) Why is b+=100; OK, but b = b+100; fails to compile?
  540.  
  541.      [*] You have code like this
  542.  
  543.        byte b = 0;
  544.        Incompatible type for =. Explicit cast needed to convert int to byte.
  545.        b = b + 100;    // compiler error message
  546.          ^
  547.        b += 100;       // works OK
  548.  
  549.      The reason is "promotion". Arithmetic expressions are promoted to the
  550.      type of the longest, floatiest operand in them, or at least to int. The
  551.      first statement involves the assignment of an expression. The
  552.      expression is promoted to 32 bits, and must be cast back down to 8
  553.      bits, like this "b = (byte) (b+100);". The second is an operator
  554.      assignment, and the cast back to byte takes place automatically. The
  555.      Java Specification says:
  556.           "A compound assignment expression of the form E1 op= E2 is
  557.           equivalent to E1 = (typecast)((E1) op (E2)), where "typecast" is
  558.           the type of E1, except that E1 is evaluated only once" [JLS
  559.           15.25.2]
  560.  
  561.      The compile-time narrowing of constants means that code such as:
  562.  
  563.      byte theAnswer = 42;
  564.  
  565.      is allowed, with no cast necessary. [JLS 5.2]
  566.  
  567.  14. (Sect. 2) How do I add two Float objects together?
  568.  
  569.      [*] You want to write code like this
  570.  
  571.              Float One;
  572.              Float Two;
  573.              Float Hard = One + Two;
  574.  
  575.  
  576.      but the compiler does not allow it.
  577.  
  578.      Java has two separate ways of representing a 32 bit floating point
  579.      number, Float and float. Float is a class, that whose sole purpose is
  580.      to "wrap" a floating point number so it can be treated as an object.
  581.      The class does not support floating point arithmetic, because the
  582.      performance would be too slow. float is a primitive type (like int)
  583.      that is used for floating point arithmetic.
  584.  
  585.      You choose one or the other depending on your predominant use. If all
  586.      you need of your floating point numbers is arithmetic, declare them to
  587.      be "float". If you need to use them as objects, for example to place
  588.      them in a Vector, declare them as "Float".
  589.  
  590.      If you need both, tough. You have to declare them one way and convert
  591.      whenever you need the capabilities of the other. Your specific code can
  592.      be written as:
  593.  
  594.              Float One = new Float(1.0);
  595.              Float Two = new Float(2.0);
  596.              Float Hard = new Float(One.floatValue() + Two.floatValue());
  597.  
  598.  
  599.      See also questions 6.n , 5.1, and 10.1.
  600.  
  601.  15. (Sect. 2) How can I put all my classes and resources into one file and
  602.      have java run it?
  603.  
  604.      [*] Use a JAR file. Put all the files in a JAR, then run the app like
  605.      this:
  606.  
  607.              java -jar [-options] jarfile Mainclass  [args...]
  608.  
  609.  
  610.  16. (Sect. 2) How can I see line numbers in a stack trace using JDK 1.1.6?
  611.  
  612.      [*] From JDK 1.1.5 on (i.e. JDK 1.1.6, JDK 1.2) the stack trace of an
  613.      uncaught exception no longer has source code line numbers. It only says
  614.      "(Compiled Code)".
  615.  
  616.      To see the line numbers where your program throws an exception, use the
  617.      command line argument in JDK 1.2:
  618.  
  619.           java -Djava.compiler=NONE myapp
  620.  
  621.      This info is well-concealed in the release note at:
  622.      http://java.sun.com/products/jdk/1.2/changes.html#aaa24
  623.  
  624.                           -----------------------------
  625.  
  626.      Specify standard Java on your new PC!
  627.  
  628.              Your new PC can come with the most up-to-date standard version
  629.              of Java, but only if you ask for it! The JavaLobby is asking PC
  630.      vendors to support Java, and to ship new machines with the Java Plug-In
  631.      pre-installed.
  632.  
  633.      See http://www.javalobby.org/servlet/PetitionServlet/pjpc
  634.      Please help the Java Lobby to promote this initiative.
  635.  
  636.      -----------------------------------------------------------------------
  637.  
  638.      Please support Java Portability.
  639.  
  640.      The biggest value of Java is its portability.
  641.         o Portability makes it easier for companies to change/upgrade
  642.           operating systems and platforms, without losing their investment
  643.           in applications software.
  644.         o Portability makes it easier for Java programmers to transfer their
  645.           skills to new employers.
  646.         o Portability makes a wider variety of software available on all
  647.           computers.
  648.      Software portability is very much in the interest of most software
  649.      developers and customers. Even if you only use Windows 95, portability
  650.      matters to you. If your software was all written in Java, it would all
  651.      just run when you moved from MS-DOS to Windows 3.1 to Windows 95 to
  652.      Windows 98 to Windows NT, and even on Windows CE. Instead, you
  653.      typically need to buy new applications software all over again when
  654.      Windows changes. Portability is not in Microsoft's interest, as it
  655.      removes a revenue stream and makes it easy for users to try other
  656.      operating systems.
  657.  
  658.      The 1998 anti-monopoly case against Microsoft revealed a Microsoft
  659.      internal memo. The memo revealed that Microsoft's "strategic objective"
  660.      was to "kill cross-platform Java." by "grow[ing] the polluted Java
  661.      market." This is Exhibit 101 (MS7 033448) in the case.
  662.  
  663.      In November 1998, a Federal judge ruled that Microsoft was probably
  664.      breaking its written agreement with Sun by distributing incompatible
  665.      Java, and that Microsoft had to stop doing that. If portability matters
  666.      to you or your users, avoid Java products from Microsoft; it is
  667.      deliberately trying to sabotage it. Microsoft's own internal documents
  668.      make this goal unambiguous. See
  669.      http://www.usdoj.gov/atr/cases/f1700/1762.htm.
  670.  
  671.      See also "The Microsoft Java Dilemma" paper at
  672.      http://www.geocities.com/ResearchTriangle/Node/2005/msjava.htm
  673.                           -----------------------------
  674.  
  675.      Windows-Specific
  676.  
  677.  17. Is there a Java implementation for Windows 3.1?
  678.  
  679.      [*] Yes. See Question 1.6 It's not that great though because Windows
  680.      3.1 has inadequate features to support great software.
  681.  
  682.  18. (Sect. 2) I'm using Win95, and my DOS window won't accept filenames
  683.      longer than 8.3.
  684.      "This program cannot be run in DOS mode"
  685.  
  686.      [*] Both these problems are resolved by the same process. Assuming
  687.      you're running the Win95/98 command.com, then you've changed the MS-DOS
  688.      Prompt options under the "Properties" menu item. In the Properties
  689.      dialog, Program->Advanced gets you a dialog. Here, make sure the
  690.      "Prevent MS-DOS-based programs from detecting Windows" checkbox is
  691.      UNCHECKED.
  692.  
  693.      If the option is checked you get exactly the kind of behavior you're
  694.      seeing. The option is unchecked by default, so it must have been
  695.      selected at some time in the past. Change it back to unchecked.
  696.  
  697.  19. (Sect. 2) I'm using Notepad to edit my files, and how can I save them
  698.      with the extension ".java"? Also, in notepad some source files have all
  699.      the characters on one line. Why is that?
  700.  
  701.      [*] First answer: put the entire filename in quotes in the save dialog.
  702.      Once you have created your first Java file, double click on it in
  703.      Explorer, select "Notepad" from the "Open with" box, and Notepad will
  704.      stop adding the spurious ".txt" to your .java files.
  705.  
  706.      Second answer: Notepad expects to see a "carriage return/line feed"
  707.      pair at the end of each line, rather than just the "newline"
  708.      (line-feed) commonly used on Unix. Use this program to expand all
  709.      newlines,
  710.  
  711.      /*
  712.       * Usage: jre crlf file1.java file2.java ... fileN.java
  713.        */
  714.  
  715.      import java.io.*;
  716.      class crlf {
  717.          public static void main(String s[]){
  718.              byte b[]; byte p;
  719.              FileInputStream is;
  720.              BufferedOutputStream os;
  721.              File f;
  722.              for (int i=0; i < s.length;i++){
  723.                  try{
  724.                      f=new File(s[i]);
  725.                      b=new byte[(int)f.length()];
  726.                      is = new FileInputStream(f);
  727.                      is.read(b); is.close();
  728.                      os = new BufferedOutputStream(
  729.                      new FileOutputStream(s[i]),b.length);
  730.                      p='?';
  731.                      for(int j=0; j < b.length; j++){
  732.                          if((p!='\r')&&(b[j]=='\n')) os.write('\r');
  733.                          p=b[j]; os.write(p);
  734.                      }
  735.                      os.flush(); os.close();
  736.                  }catch(IOException e){
  737.                      System.err.println(e.toString());
  738.                  }
  739.              }
  740.          }
  741.      }
  742.  
  743.  
  744.      The source code is to show new users a way to make a simple program
  745.      which can read a file and write it out buffered.
  746.  
  747.      Compile with "javac crlf.java" and run with
  748.      java crlf outfile.txt
  749.      or just use Wordpad instead of Notepad. Wordpad is under
  750.      Start->Programs->Accessories->WordPad
  751.  
  752.  20. (Sect. 2) How do I fix the message about "out of environment space"?
  753.  
  754.      [*] This occurs under Windows when you have long CLASSPATH names. You
  755.      need to increase the environment space. On Windows 95,8 put this in
  756.      your c:\windows\system.ini
  757.  
  758.              [NonWindowsApp]
  759.              CommandEnvSize=4096
  760.  
  761.  
  762.      On NT you can right-click on My Computer, select System Properties then
  763.      go to the Environment tab and then increase COMSPEC to the value you
  764.      want.
  765.  
  766.      The previous suggestion to put this in your config.sys:
  767.  
  768.              shell=command /e:4096
  769.  
  770.  
  771.      apparently causes you to create two copies of command.com which wastes
  772.      memory.
  773.  
  774.                        -------------------------------
  775.  
  776. 3. General Information
  777.  
  778.   1. (Sect. 3) Is Java "Open" or "Proprietary"?
  779.  
  780.      [*] The Java specification is publicly available, and anyone is free to
  781.      do clean-room implementations of the JVM and core Java API's. Sun
  782.      includes a perpetual, irrevocable, free and royalty-free license in the
  783.      front of the Addison-Wesley books containing the specification.
  784.  
  785.      Sun also provides free access to the Java source. See
  786.      http://java.sun.com/communitysource/
  787.  
  788.      Using the Java trademark does requires licensing from Sun. It is not
  789.      clear if the Embedded or Personal Java specifications are open, as it
  790.      is not clear if a clean-room implementation may be done without
  791.      licensing from Sun.
  792.  
  793.      The relative openness of Java contrasts with systems that are only
  794.      available from one vendor, whose interfaces are developed in secret,
  795.      without an open process for others to participate, whose owners do not
  796.      allow competing implementations of the same API, and whose owners
  797.      change the APIs as a strategic weapon against competitors. Typically,
  798.      such systems also feature "private" APIs that are published late or not
  799.      published at all, to allow the single vendor to gain a competitive
  800.      advantage for their other products. Typically such proprietary systems
  801.      do not make the source code available for inspection by all.
  802.  
  803.   2. (Sect. 3) What is the best way to refer someone to the FAQ when they
  804.      ask a question I know is answered there?
  805.  
  806.      [*] The Java Programmers FAQ (at http://www.afu.com) answers your
  807.      question in section N.n. ...
  808.  
  809.      This gives them the answer, and shows them where to go for future
  810.      questions. It also demonstrates that the FAQ can answer their
  811.      questions, supplying an incentive to go there next time. It's regarded
  812.      as elementary politeness to look for the FAQ of a newsgroup and read it
  813.      before posting any questions.
  814.  
  815.      In general, FAQs for any newsgroup are available by looking at past
  816.      postings in a group, or by searching Deja News (see Q 1.4), or via
  817.      anonymous FTP at directories under ftp://rtfm.mit.edu. The pathnames
  818.      are called things like
  819.      /pub/usenet-by-group/comp.lang.java.programmer/Java_Programmers_FAQ
  820.      which may help you get to the right one directly, as it takes some time
  821.      to get a directory listing there. Alternatively, you can look for
  822.      newsgroup names on the same ftp site by going to the same site and
  823.      looking under /pub/usenet-by-hierarchy/. That has subdirectories such
  824.      as alt/, ba/, ca/, comp/, and subdirectories under them such as
  825.      /pub/usenet-by-hierarchy/comp/lang/ and so on. This helps you explore
  826.      the world of newsgroups with FAQs.
  827.  
  828.      If you do not have anonymous FTP access, you can access the
  829.      rtfm.mit.edu archives by mail server as well. Send an E-mail message to
  830.      mail-server@rtfm.mit.edu with "help" in the body for more information.
  831.      "RTFM" stands for "Read The effing Manual" - you must expect to put in
  832.      some time and effort to master a new area of study.
  833.  
  834.      If you want to look at the definition of Internet standards like FTP,
  835.      telnet, visit the IETF site at http://www.ietf.org where all the RFC's
  836.      (Request For Comments) can be found.
  837.  
  838.   3. (Sect. 3) What if my question is not answered in this FAQ?
  839.  
  840.      [*] Go to http://www.dejanews.com/home_ps.shtml
  841.      In May 1999, Dejanews changed their name to Deja.com, and their web
  842.      design to a truly horrible garish interface, covered with ads and
  843.      harder to search. Consider using these search sites instead:
  844.      http://www.exit109.com/~jeremy/news/deja.html
  845.      http://www.dogpile.com
  846.      http://www.google.com
  847.      http://www.hotbot.com
  848.      http://www.mamma.com
  849.         o Under "Newsgroups" enter "comp.lang.java.programmer" (or whatever)
  850.         o Under "Subject" enter "Frotteur" (or other topic you find
  851.           pressing)
  852.         o Click "Create Filter"
  853.         o It will go to a new document, and you should click the link
  854.           labeled
  855.  
  856.           nnn Documents (nnn is some number).
  857.  
  858.      The chances are that you will find several answers to your question.
  859.      Some may not be complete or completely accurate however. That is the
  860.      nature of Usenet, and free information. If you still don't have an
  861.      answer, then post your question on the most appropriate of the
  862.      newsgroups. Don't spam the newsgroups by posting to multiple groups.
  863.      Knowledgeable posters tend to ignore questions like that.
  864.  
  865.      Also look at http://sunsite.unc.edu/java/cgi-bin/query
  866.      and look at http://asknpac.npac.syr.edu/ for a Java newsgroup search.
  867.  
  868.      http://www.javaworld.com/search.html can search the Javaworld
  869.      newspaper.
  870.  
  871.   4. (Sect. 3) What Java mailing lists are there?
  872.  
  873.      [*] There are quite a few Java mailing lists.
  874.      http://java.miningco.com/msub7.htm has a comprehensive list.
  875.  
  876.   5. (Sect. 3) Where can I look at the definitive Java Language
  877.      Specification?
  878.  
  879.      [*] This is available online at:
  880.           http://java.sun.com/docs/books/jls/html/index.html (Java 1.0)
  881.  
  882.      and the Java 1.1 inner classes document at:
  883.           http://java.sun.com/products/jdk/1.1/docs/guide/innerclasses/
  884.           spec/innerclasses.doc.html
  885.  
  886.      and the other Java 1.1 update at:
  887.           http://java.sun.com/docs/books/jls/html/1.1Update.html
  888.  
  889.      and the Java API is at:
  890.           http://java.sun.com/products/jdk/1.1/docs/api
  891.  
  892.      It is also available as a book in printed form (details at website).
  893.      Also see the "Clarifications and Amendments"
  894.      http://java.sun.com/docs/books/jls/clarify.html.
  895.  
  896.      You can also see the virtual machine (execution environment)
  897.      specification at
  898.      http://docs.sun.com:80/ab2/coll.127.1/@Ab2CollToc?subject=java
  899.  
  900.   6. (Sect. 3) Where can I find information about future Java APIs?
  901.  
  902.      [*] JavaSoft has followed a policy of creating new APIs in consultation
  903.      with leading industry participants, then posting the draft
  904.      specification for public review and comments. Check the JavaSoft
  905.      roadmap of new APIs and products at
  906.      http://java.sun.com:80/products/api-overview/index.html
  907.      Also, some APIs that are under consideration, possibly for JDK 1.2 are
  908.      at:
  909.           http://java.sun.com/products/jdk/preview/docs/
  910.  
  911.   7. (Sect. 3) I'm looking for a Java style guide on naming conventions.
  912.  
  913.      [*] Check out the section "Naming Conventions" in the language
  914.      specification
  915.           http://java.sun.com/docs/books/jls/html/6.doc.html#11186
  916.  
  917.      Also take a look at Doug Lea's draft coding standard -
  918.           http://gee.cs.oswego.edu/dl/html/javaCodingStd.html
  919.  
  920.      See also naming conventions for some basic rules of thumb.
  921.  
  922.   8. (Sect. 3) How do I check on known bugs in the JDK?
  923.  
  924.      [*] Look at the Java Developer Connection at http://java.sun.com/jdc.
  925.  
  926.      All the Java bugs that Sun knows about are listed there, with the
  927.      exception of security-related bugs. The legal department in Sun vetoed
  928.      the open publication of security bugs. After you have checked that the
  929.      bug is not already listed, you can submit a bug report through:
  930.      http://java.sun.com:80/cgi-bin/bugreport.cgi
  931.      You should check that the bug doesn't already exist for two reasons:
  932.      first, you might find the bug with a workaround listed. Second, you
  933.      don't want to waste everyone's time with a duplicate bug report.
  934.  
  935.      You can also send in an RFE (Request For Enhancement) or ease-of-use
  936.      issue there. You can even vote on the priority you would assign to a
  937.      particular bug fix! Join the Java Developer Connection (it's free) by
  938.      going to http://java.sun.com/jdc. Then browse
  939.      http://developer.javasoft.com/developer/bugParade/#votes
  940.  
  941.   9. (Sect. 3) What computers have Java ports? Is there a port to Win 3.1?
  942.  
  943.      [*] A partial list of JDK ports is available from
  944.      http://java.sun.com/cgi-bin/java-ports.cgi
  945.      An (impressive) list of the systems that the GPL Kaffee JVM runs on is
  946.      at http://www.transvirtual.com/ports.html
  947.  
  948.      A list of the software updates you should install to run Java on
  949.      Solaris is at
  950.      http://java.sun.com/products/jdk/1.2/install-solaris-patches.html#2.6
  951.  
  952.      There are several Java ports to Win 3.1. IBM's ADK1.02 is available at
  953.      the following locations:
  954.         o http://ncc.hursley.ibm.com/javainfo/latest/answers/faq0.html
  955.         o http://www.alphaworks.ibm.com/formula
  956.      IBM offers a port to Linux, as do others. The IBM Jikes port is at
  957.      http://www.alphaworks.ibm.com/ There is a large amount of useful
  958.      software there, including a profiling tool called jinsight.
  959.  
  960.      Netscape Navigator for Win3.1 has Java support. Java will never be
  961.      well-supported under Win3.1 because Win3.1 lacks the basic features
  962.      expected of a modern OS (primarily lengthy filenames and multithreading
  963.      support).
  964.  
  965.      Also take a look at JavaSoft's JavaPC kit that can switch a PC into a
  966.      thin client Java system (and back to Win3.1/DOS when you want). It's
  967.      meant for software OEMs and large corporations running lots of older
  968.      PCs, but you can use it on the latest Pentium II too. Details are at
  969.      http://java.sun.com/products/javapc/index.html. JavaPC is available now
  970.      for $100, runs on 486's with 8Mb or more Unlike the 16-bit versions of
  971.      Netscape Navigator and Microsoft Internet Explorer, which provide a
  972.      Java Virtual Machine that is only compliant with the JDK 1.0.2 API, the
  973.      JavaPC software allows IS managers to deploy JDK 1.1-compatible Java
  974.      applications on PCs running DOS and Windows 3.x.
  975.  
  976.  10. (Sect. 3) Where can I find information on Java 3D?
  977.  
  978.      [*] The Java 3D FAQ at http://tintoy.ncsa.uiuc.edu/~srp/java3d/faq.html
  979.      may have the answers you're looking for. It contains general
  980.      information about Java 3D, as well as programming tips.
  981.  
  982.  11. (Sect. 3) Where can I find information about Java Certification?
  983.  
  984.      [*] Sun is sponsoring an examination which programmers worldwide can
  985.      take. Those passing can use the designation "Sun Certified Java
  986.      Programmer". There is also a second-level test, involving writing a
  987.      program to spec, and taking a further test. That results in the
  988.      qualification "Sun Certified Java Developer". You can find out all
  989.      about the exam at:
  990.           http://www.sun.com/service/suned/
  991.  
  992.      and then search for "sun certified java". It costs $150 to sit the Java
  993.      Programmer exam. It is not trivial to pass the Java certification exam.
  994.      It requires understanding the objectives of the test, and the material
  995.      that is tested for. These are given, along with sample questions, at
  996.      the URL mentioned above.
  997.  
  998.      There is a Java certification FAQ at: http://www.marcusgreen.co.uk
  999.  
  1000.  12. (Sect. 3) How can I find links to recent news about Java?
  1001.  
  1002.      [*] This site contains links to late-breaking online news stories about
  1003.      Java. http://www.intelligence.com/java/
  1004.      Another good Java news source is http://www.nikos.com/javatoys.
  1005.  
  1006.      This site is a fine site for programmers who want to be well-informed
  1007.      about computer industry topics. It has a lot of coverage of Linux as
  1008.      well as more general news. http://slashdot.org Highly recommended.
  1009.  
  1010.      This site is a source of independent news and commentary on the
  1011.      computer industry, including Java. http://www.pjprimer.com/media.html.
  1012.      You have to subscribe ($10/year, 30 day free trial).
  1013.  
  1014.  13. (Sect. 3) What are the folks at GNU doing with Java?
  1015.  
  1016.      [*] First note that the URLs in this section change quickly, and soon
  1017.      become outdated. If you have an update, send it in. There is a Gnu Java
  1018.      page at http://www.gnu.org/software/java/java.html
  1019.      Guava (a GPL'd Java compiler) can be found at
  1020.           ftp://ftp.yggdrasil.com/pub/dist/devel/compilers/guavac/
  1021.      Alternatively, it may be available at
  1022.      http://http.cs.berkeley.edu/~engberg/guavac
  1023.      Work is progressing on the Cygnus Java frontend to gcc. See
  1024.      http://www.cygnus.com/product/javalang/
  1025.  
  1026.      Kaffe (a JVM) can be found at
  1027.           http://www.transvirtual.com This is Tim Wilkenson's company
  1028.           devoted to commercializing the Kaffe JVM for the embedded systems
  1029.           market. He also releases a version of it under the GPL. It also
  1030.           comes with a the beginnings of a class library and the Pizza
  1031.           compiler.
  1032.  
  1033.      Classpath is a free implementation of Sun's Java libraries (v1.1),
  1034.      being developed for the GNU Project ( http://www.gnu.org). Information
  1035.      regarding classpath is at http://www.classpath.org They aim to develop
  1036.      a 100% free drop in replacement for Sun's class libraries, targeting
  1037.      first the Japhar JVM (below). They are always looking for help, so feel
  1038.      free to stop by and volunteer.
  1039.  
  1040.      See also http://www.japhar.org This is the Hungry Programmer's JVM.
  1041.      Currently it is development grade only.
  1042.  
  1043.  14. (Sect. 3) What is "San Francisco"?
  1044.  
  1045.      [*] San Francisco is the code name for a very large Java project led by
  1046.      IBM, and involving other companies. The project is to provide a Java
  1047.      framework for data processing applications. A large number of classes
  1048.      are provided for general ledger, sales order, inventory management,
  1049.      etc., and these classes can be extended and customized for particular
  1050.      industries (vertical markets). It is a large and ambitious software
  1051.      project.
  1052.  
  1053.      IBM's SF project competes with products from companies like SAP and
  1054.      Baan. Of course, the SF project is multi-platform and uses Java beans
  1055.      and GUI interfaces. More information on SF is available at
  1056.      http://www.ibm.com/Java/Sanfrancisco
  1057.  
  1058.  15. (Sect. 3) What large Office-style or other applications have been
  1059.      written in Java?
  1060.  
  1061.      [*] Well, the first one to consider is IBM's San Francisco project,
  1062.      mentioned above. There is also Lotus's e-suite - a suite of Java
  1063.      applets and beans including a spreadsheet and a word processor. See
  1064.      http://esuite.lotus.com. These became available in March 1998.
  1065.  
  1066.      Another office suite in Java is Applix Anyware at
  1067.      http://www.applix.com/anyware/index.htm. Applix became available in
  1068.      downloadable demo form in April 1998.
  1069.  
  1070.      Yet another is Star Division's Client/Server Office. It is an office
  1071.      suite with the client part written in Java and able to run on
  1072.      JavaStations. The server part will run on Solaris, NT, OS/390, and
  1073.      AS/400. The older (non-Java) version is bundled with all Sun
  1074.      workstations sold in Germany. The Linux version is freely downloadable
  1075.      from http://www.stardivision.com.
  1076.  
  1077.      Another is Digital Harbor's Wav word processor. It supports component
  1078.      software, and it runs in 1MB, not the 114Mb of the latest MS Word. A
  1079.      free trial is avilable. See: http://www.digitalharbor.com
  1080.  
  1081.      Another Java application is Formula One for Java, an Excel-compatible
  1082.      spreadsheet written in 100% pure Java, and available for all systems
  1083.      that support Java. It runs as a Java Bean, so can easily be assembled
  1084.      as one component of a larger system. It also runs as an application,
  1085.      and as an applet! Formula One is a product of Visual Components, Inc.
  1086.      See http://www.f1j.com.
  1087.  
  1088.      Another one is Ncode Research Inc. who write Java viewers for office
  1089.      suites. They are file-format specialists. Their mission is to make all
  1090.      popular file formats available for the Java platform. They write 100%
  1091.      Pure Java viewers for Word, Excel and PowerPoint (including Office 95
  1092.      and 97 formats). See http://www.ncode.com/
  1093.      Another company operating in the same space is JSoft, at
  1094.      http://www.jsoftinc.com
  1095.  
  1096.      Intentia, the 8th largest ERP vendor (annual sales of $320 million),
  1097.      has moved their entire suite of applications (Movex - covering 8
  1098.      markets) from RPG to Java - 20 million lines worth. See their press
  1099.      release.
  1100.  
  1101.      However, the industry is seeing few new office productivity
  1102.      applications written in any language. The niche for single-user office
  1103.      productivity applications is already dominated by Microsoft products,
  1104.      and it is unrealistic to think that Java software will unseat
  1105.      shrink-wrapped software simply because it is written in Java. This is
  1106.      why Corel replanned its Java rewrite of Corel Office before taking it
  1107.      to FCS. When Corel did that, it also increased its investment in Java
  1108.      from 33% of R&D budget to 50%, at the expense of Windows.
  1109.  
  1110.      Most of Java development is taking place for custom applications
  1111.      internal to a company. Most programmers of any kind have never worked
  1112.      on MS Office, but work on internal applications, and so it is with
  1113.      Java. These projects don't have the high profile of major vendors'
  1114.      products, but they are the mainstay of the industry. There are many
  1115.      companies working on Java Beans, like http://www.quadbase.com who have
  1116.      Java graphing software (see also GraphMaker mentioned later in this
  1117.      document). EspressChart is a Java Bean that gives you the ability to
  1118.      add 2D and 3D graphs in your applications/applets. This bean is easy to
  1119.      use, 100% Java, and runs anywhere.
  1120.  
  1121.      There are some excellent Java games applets at
  1122.      http://www.javaarcade.com Check out the pinball -- dig that crazy
  1123.      rhythm, man.
  1124.      There are more good Java games applets at
  1125.      http://www.frontiernet.net/~imaging/java_games.html
  1126.      and at http://www.gamesdomain.co.uk/GamesArena
  1127.      If you want to use Java to learn math & computer graphics, visit
  1128.      http://www.frontiernet.net/~imaging/math_is_a_game.html
  1129.  
  1130.      ObjectDesign Inc., has an ODBMS written in 100% java. The product is
  1131.      named PSE Pro for Java. See http://www.objectdesign.com
  1132.      Another database written in Java is available from
  1133.      http://www.cloudscape.com.
  1134.      Another database written in Java is available from
  1135.      http://www.instantdb.co.uk. InstantDB is available free to
  1136.      non-commercial organizations, and is very well documented and
  1137.      maintained. (Recommended!)
  1138.      Finally, note that Sun's Java compiler is written in Java. This is a
  1139.      really big application in widespread use on millions of platforms. The
  1140.      compile command "javac test.java" is equivalent to
  1141.  
  1142.          java sun.tools.javac.Main test.java
  1143.  
  1144.  
  1145.      javac has a script wrapper just to set the heap size as a command line
  1146.      argument, as you can do in your own programs.
  1147.  
  1148.  16. (Sect 3.) What Java User Groups are there?
  1149.  
  1150.      [*] There are scores of Java User groups around the world, mostly in
  1151.      urban areas, and centers of software technology development. A partial
  1152.      list with contact information can be found at
  1153.      http://sunsite.unc.edu/javafaq/usergroups.html.
  1154.      If you can't find a user group in your area/school, it's easy and
  1155.      satisfying to start one.
  1156.  
  1157.  17. (Sect 3.) What is a Java Bean?
  1158.  
  1159.      [*] A Java bean is a Java class that follows some simple conventions.
  1160.      Because it follows conventions, it can easily be processed by a
  1161.      software tool that connects Beans together at runtime. Java beans are
  1162.      reusable software components.
  1163.  
  1164.      Think of Java beans as being the software equivalent of Lego[tm]
  1165.      bricks. Instead of plugging together plastic bricks, you can easily
  1166.      plug together classes, and have them fit and work with each other. See
  1167.      http://www.jc100.org/
  1168.      See the Java Bean FAQ at http://java.sun.com/beans/faq/faq.general.html
  1169.  
  1170.  18. (Sect 3.) Where can I find examples of the use of the Java class
  1171.      libraries?
  1172.  
  1173.      [*] The two volumes of "Java Class Libraries" by Chan, Lee and Krama
  1174.      published by Addison Wesley, have extensive examples of how to use the
  1175.      standard libraries. One programmer comments "When I need to use an
  1176.      unfamiliar area of the class libraries one of the first things I do is
  1177.      read their examples." You can see them online at
  1178.      http://java.sun.com/docs/books/chanlee/second_edition/vol1/examples.html
  1179.      and http://java.sun.com/docs/books/chanlee/second_edition/examples.html
  1180.  
  1181.  19. (Sect 3.) How can I find out exactly what version of Java I have on my
  1182.      system?
  1183.  
  1184.      [*] On a Solaris system, you can use the pkginfo command, like this:
  1185.  
  1186.         pkginfo -l SUNWjvrt
  1187.  
  1188.      It will give a reply like this:
  1189.  
  1190.         PKGINST:  SUNWjvrt
  1191.            NAME:  JavaVM run time environment
  1192.        CATEGORY:  system
  1193.            ARCH:  sparc
  1194.         VERSION:  1.1.6,REV=1998.07.30.16.21
  1195.         BASEDIR:  /
  1196.          VENDOR:  Sun Microsystems, Inc.
  1197.       ...etc
  1198.  
  1199.      You may also try
  1200.  
  1201.         java -fullversion
  1202.  
  1203.      Although that's not an officially-supported command option, and has
  1204.      gone away in JDK 1.2. Try also
  1205.  
  1206.         java -version
  1207.  
  1208.  20. (Sect 3.) What Java newsgroups are there?
  1209.  
  1210.      [*]
  1211.  
  1212.  
  1213.           comp.lang.java.beans
  1214.           comp.lang.java.corba
  1215.           comp.lang.java.databases
  1216.           comp.lang.java.gui
  1217.           comp.lang.java.help (it renamed comp.lang.java.setup)
  1218.           comp.lang.java.machine (it renamed comp.lang.java.tech)
  1219.           comp.lang.java.programmer (it renamed c.l.j.api and c.l.j.misc)
  1220.           comp.lang.java.advocacy (argue all day with anonymous shills)
  1221.           comp.lang.java.softwaretools
  1222.           alt.comp.lang.java-games
  1223.  
  1224.      New Java newsgroups are added every so often. Try not to crosspost.
  1225.  
  1226.                        -------------------------------
  1227.  
  1228. 4. Compilers and Tools
  1229.  
  1230.   1. (Sect. 4) Is there a lex and yacc or preferably a flex and bison
  1231.      equivalent for Java?
  1232.  
  1233.      [*] There is a lex equivalent called JavaLex and a yacc equivalent
  1234.      called CUP.
  1235.  
  1236.      LALR(1) parser JavaLex and JavaCup:
  1237.      http://www.cs.princeton.edu/~appel/modern/java/
  1238.  
  1239.      LL(k) parser JavaCC: http://www.suntest.com/JavaCC/
  1240.      LALR(1) parser SableCC from McGill U.
  1241.      http://www.sable.mcgill.ca/sablecc/index.html is generously made
  1242.      available under GNU license.
  1243.  
  1244.   2. (Sect. 4) Where can I find a byte code obfuscator?
  1245.  
  1246.      [*] Java Obfuscators replace the original class, field and methods
  1247.      names in the bytecode with meaningless strings. Second generation
  1248.      obfuscators are now appearing that also obfuscate the control flow and
  1249.      encrypt String literals. People use obfuscators on their applets if
  1250.      they want to hide their code from others. Generally, you wouldn't do
  1251.      this with software that you put on your website for others to enjoy. It
  1252.      runs counter to the "open source" philosophy of learning from other's
  1253.      code and allowing them to learn from yours.
  1254.  
  1255.      Zelix KlassMaster is a commercially supported obfuscator. It has a free
  1256.      evaluation version at http://www.zelix.com/klassmaster
  1257.      Another commercially supported obfuscator, with a downloadable free
  1258.      trial is at http://www.4thpass.com/SourceGuard. There are also some
  1259.      free works from students and others. http://www.primenet.com/~ej/
  1260.      http://www.math.gatech.edu/~mladue/HoseMocha.java
  1261.  
  1262.      Some people have reported problems using these with JDK 1.1.
  1263.  
  1264.      This obfuscator has been updated to be fully compatible with JDK 1.1:
  1265.      http://www.monmouth.com/~neil/Obfuscate.html
  1266.  
  1267.      Obfuscators are intended to foil decompilers. Decompilers translate
  1268.      byte code back into Java source code. Mocha was the first and most well
  1269.      known of the decompilers; it's no longer supported. There is a
  1270.      decompiler (written in C++) at
  1271.           http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
  1272.      Because it is in C++, there are different versions for every
  1273.      architecture (hah!) There are also commercial products, such as
  1274.      SourceAgain from
  1275.           http://www.ahpah.com/
  1276.  
  1277.      There's a very good Java Code Engineering and Reverse Engineering FAQ
  1278.      page at http://www.meurrens.org/ip-Links/Java/codeEngineering/.
  1279.  
  1280.   3. (Sect. 4) Which program is used to create .zip files compatible with
  1281.      the java* programs?
  1282.      (e.g. classes.zip, moz3_0.zip)
  1283.  
  1284.      [*] Use the jar-tool from JDK1.1(.1):
  1285.           jar [ options ] [manifest] destination input-file [input-files]
  1286.  
  1287.      E.g.:
  1288.           jar cvf myJarFile.jar *.class
  1289.  
  1290.      creates a compressed archive. And watch out -- the order of the options
  1291.      ("cvf") determine the order of the arguments!
  1292.           jar cvfO myJarFile.zip *.class
  1293.  
  1294.      creates it fullsize (uncompressed) (note the 'O'-option used for
  1295.      JDK1.0.2)
  1296.  
  1297.      On Unix you can also use:
  1298.           zip -rn ".class" my_file.zip *
  1299.  
  1300.      Info-ZIP home page: http://www.cdrom.com/pub/infozip/
  1301.      Latest source code: ftp://ftp.uu.net/pub/archiving/zip/src/zip21.zip
  1302.  
  1303.      Netscape's command line version of its JAR packager and signing tool is
  1304.      called "zigbert". They also have a signing tool with GUI written in
  1305.      Java. More info
  1306.      http://developer.netscape.com/software/signedobj/jarpack.html
  1307.  
  1308.      If you zip your .class files for JDK 1.0.2 (for 1.1 you'll use a Jar):
  1309.        1. zip your files uncompressed (can use WinZip 6.2 up);
  1310.                Unix command:
  1311.  
  1312.                zip -r0 classes.zip <directories>
  1313.  
  1314.        2. Make sure the main class has no parent directory inside the
  1315.           archive, (in other words, don't build an archive with
  1316.           foo/bar/myMain.class, unless your myMain is in a package called
  1317.           foo.bar. Instead start it at myMain.class). Your packages must be
  1318.           placed in the archive using their corresponding filesystem
  1319.           pathnames.
  1320.        3. Put the archive in the same directory as the .html page.
  1321.        4. Put something like the following tag in the .html file:
  1322.  
  1323.           <APPLET CODEBASE="."
  1324.                   ARCHIVE=my_zip_file.zip,myOtherZip.zip,thirdfile.zip
  1325.                   CODE="my_main_class.class"
  1326.                   WIDTH=600 HEIGHT=250>
  1327.               </APPLET>
  1328.  
  1329.  
  1330.      From JDK 1.1 on, an example of the applet tag used with a jar file is
  1331.  
  1332.      <APPLET ARCHIVE=myfile.jar
  1333.                      CODE=myapplet.class
  1334.                      WIDTH=600 HEIGHT=250>
  1335.              </APPLET>
  1336.  
  1337.  
  1338.      These lines will use an applet called myapplet that can be found in the
  1339.      jarfile myfile.jar. An example applet tag of a jar file used to hold
  1340.      classes in packages is
  1341.  
  1342.      <APPLET ARCHIVE="myclasses.jar"
  1343.                      CODE="linden.net.MyApplet.class"
  1344.                      WIDTH=480
  1345.                      HEIGHT=120>
  1346.              </APPLET>
  1347.  
  1348.  
  1349.      You can supply several jar filenames in a comma-separated list. Jar
  1350.      files are in compressed PKZIP format.
  1351.  
  1352.   4. (Sect. 4) Can I compile a Java program to a binary executable, .exe on
  1353.      a PC?
  1354.  
  1355.      [*] Compiling into native code destroys portability, which is one of
  1356.      the main benefits of Java. If you want to create a native executable
  1357.      because you wanted to make it easy to distribute and use programs,
  1358.      consider a Jar file instead.
  1359.      Some companies make products that do this. See the webpages for
  1360.      Symantec http://www.symantec.com, Supercede http://www.supercede.com,
  1361.      and Tower Technology http://www.twr.com. The first two are targeted to
  1362.      Windows. Tower Technology supports several flavors of Unix.
  1363.  
  1364.      Also, there is a native Java compiler from IBM, known as the HPJ (High
  1365.      Performance Java) compiler. One user has reported that it created a 2Mb
  1366.      executable from a 12K java file, and did not run any faster. See
  1367.      http://www.alphaworks.ibm.com/
  1368.  
  1369.      See also Instantiations JOVE http://www.instantiations.com/jove.htm,
  1370.      the paper about the Toba project
  1371.      http://research.microsoft.com/research/lt/toddpro/papers/coots97.pdf,
  1372.      Network World, "Vendors Rush To Speed Java Performance", Feb 9 1998, at
  1373.      http://www.nwfusion.com/news/0209java.html
  1374.  
  1375.      Compiling to native code takes away the most significant benefit of
  1376.      Java: portability of executables. Further, if you want your Java DLL
  1377.      (or .exe) to interact with C++, you'll have to specify which specific
  1378.      C++ compiler and/or actually compile some sort of linkage via the
  1379.      appropriate C++ compiler. C++ does not have a standard ABI, so there is
  1380.      a big problem with interoperability. Every C++ compiler uses a
  1381.      different object model, a different way of laying out class members,
  1382.      and a different way of "mangling" names for the linker.
  1383.  
  1384.      C is much simpler. The only question here is how structures are
  1385.      "packed" (i.e., are integers aligned on four-byte bounds?). All the C++
  1386.      compilers can interact with C code, thanks to 'extern "C"'
  1387.      declarations.
  1388.  
  1389.      Consider carefully why you want to compile to a native executable, and
  1390.      whether there is a Java way to accomplish your goal. There may be a
  1391.      good reason for compiling to native code, but it needs to be thought
  1392.      through.
  1393.  
  1394.   5. (Sect. 4) How can I performance profile my Java code?
  1395.  
  1396.      [*]java -prof MyClass
  1397.  
  1398.      produces some basic output in a file called java.prof, showing the
  1399.      number of times methods were invoked. The output lines are of the form:
  1400.           # of calls     method called      called by        time spent
  1401.      On a Unix system, you can sort the file with something like
  1402.  
  1403.      sort -r +82 <java.prof > java.sort
  1404.  
  1405.      More and better Java tools are a third party opportunity. One Java
  1406.      profiler is JProbe Profiler, available from http://www.klg.com/jprobe.
  1407.      JProbe is said to be easy to use. Another profiler is OptimizeIt,
  1408.      available from http://www.optimizeit.com. Each of these profilers has
  1409.      performance tuning, which shows which methods took how much time, and
  1410.      also memory tuning, which shows what objects are in memory and how they
  1411.      were allocated. Both are important things to know. The latest version
  1412.      of the CodeWarrior IDE http://www.metrowerks.com has a time-based
  1413.      profiler for Java code. Java Workshop from Sun also has a time-based
  1414.      profiler.
  1415.  
  1416.      JDK 1.2 comes with some limited profiling capability built-in.
  1417.      Depending on your needs, it may be all that you need. Execute the
  1418.      following to get a short summary of what you can do:
  1419.  
  1420.         java -Xrunhprof:help
  1421.  
  1422.      For example, you can see which methods are taking the most time to
  1423.      execute, in the context of particular stack traces.
  1424.  
  1425.   6. (Sect. 4) When I use javadoc and I click on any java class included in
  1426.      the JDK why do I get this message?
  1427.  
  1428.          Netscape is unable to find the file or directory named:
  1429.          /E|/Jwrkshop/JDK/bin/java.lang.Throwable.html
  1430.  
  1431.  
  1432.      [*] References to the JDK classes assume that all generated html files
  1433.      are in the same directory and, in fact, that all files for all classes
  1434.      referenced are generated at the same time. There is no way to generate
  1435.      files incrementally and have them all reference each other, as you
  1436.      would like.
  1437.  
  1438.      As long as you have source for everything involved (including the JDK
  1439.      and all third-party classes), you can list all of your packages and all
  1440.      of the others on the javadoc command line and generate the whole set at
  1441.      once, but it is burdensome. Of course, if you receive any libraries as
  1442.      .class files, even this workaround will not suffice.
  1443.  
  1444.      Also javadoc will not generate the image files - you need to get them
  1445.      from the images directory under the JDK API documentation files. You
  1446.      can just copy the entire directory into your own doc directory. javadoc
  1447.      is a very nice concept, with a few implementation flaws.
  1448.  
  1449.   7. (Sect. 4) I'm working on a project with lots of classes and I use the
  1450.      JDK. A recompile from scratch takes forever when I do it a class at a
  1451.      time. How do I recompile everything?
  1452.  
  1453.      [*] The first way is
  1454.           javac *.java
  1455.  
  1456.      Another way is
  1457.           javac -depend tip.java
  1458.  
  1459.      where "tip.java" is a class "at the tip of the iceberg", i.e. that
  1460.      depends on (uses) all the other classes. Typically, this may be your
  1461.      main class. However, "-depend" is known to be buggy and cannot be
  1462.      relied upon. It also doesn't issue compile commands in parallel to make
  1463.      use of multi-processor systems.
  1464.  
  1465.      Without the "-depend" option, the standard "javac files" doesn't look
  1466.      beyond the immediately adjacent dependencies to find classes lower down
  1467.      the hierarchy where the source has changed.
  1468.  
  1469.      The -depend options searches recursively for depending classes and
  1470.      recompiles it. This option doesn't help when you have dynamically
  1471.      loaded classes whose names cannot be determined by the compiler from
  1472.      the dependency graph. E.g. you use something like
  1473.           Class.forName(argv[0]);
  1474.  
  1475.      The author of the code using those classes should make sure that those
  1476.      classes are mentioned in a Makefile.
  1477.  
  1478.   8. (Sect. 4) Why do I get the java.lang.UnsatisfiedLinkError when I run my
  1479.      Java program containing Native Method invocations?
  1480.  
  1481.      [*] Your program is not able to find your shared library or DLL.
  1482.  
  1483.      On Windows 95/NT, make sure that the DLL exists in a path that is
  1484.      included within the PATH environment variable. (This need is true for
  1485.      both standard (untrusted) applications and trusted applets. At least,
  1486.      if you use the Java Plug-in to give yourself standard Java inside a
  1487.      browser).
  1488.  
  1489.      On Solaris, make sure that the environment variable LD_LIBRARY_PATH
  1490.      includes the path of your shared library.
  1491.  
  1492.      Note that jdb looks for libraries with "_g" appended to their names.
  1493.      Thus, if you intend to use jdb on a Java application that invokes
  1494.      native methods, you must ensure that the appropriately named libraries
  1495.      are in jdb's path. The "debug" nm libraries can simply be renamed
  1496.      copies of the nondebug libraries.
  1497.  
  1498.      For example, if your app invokes native methods in a library named
  1499.      mynm.dll (on Windows) or mynm.so (on Solaris), make a copy in the same
  1500.      directory and name it mynm_g.dll or mynm_g.so.
  1501.  
  1502.   9. (Sect. 4) An anonymous class can't seem to access a private outer
  1503.      method. Why is that?
  1504.  
  1505.      [*] It's a known bug in the JDK 1.1.4. The code is:
  1506.  
  1507.          public class MyDialog {
  1508.  
  1509.                  void Setup() {
  1510.                  addWindowListener( new WindowAdapter() {
  1511.                        public void windowClosing(WindowEvent e) {
  1512.                               myCloseWindow(); }
  1513.                        }
  1514.                        );     // anon inner class
  1515.                  }
  1516.  
  1517.              private void myCloseWindow() {   // private outer method
  1518.                  dispose();
  1519.              }
  1520.          }
  1521.  
  1522.      This code sends javac into an infinite loop. The workaround is to make
  1523.      the private method non-private, or to make the inner class a named
  1524.      class. Sun put a workaround in the compiler to silently set the field
  1525.      to package access.
  1526.  
  1527.  10. (Sect. 4) What are the major Java releases and their contents?
  1528.  
  1529.      [*] There have been three Java releases from Sun so far, plus a number
  1530.      of bugfix (dot-dot) releases. The releases are:
  1531.         o JDK 1.0.2
  1532.           This was the release FCS in May 1996. It had some security fixes
  1533.           over JDK 1.0.
  1534.         o JDK 1.1
  1535.           This release (Feb 1997) introduced a new event model in the window
  1536.           system. It also made JDBC support and beans support a standard
  1537.           feature. It changed and standardized the native code interface to
  1538.           JNI. It also introduced inner classes.
  1539.         o JDK 1.2
  1540.           This release (Dec 1998) made the Swing library a standard feature.
  1541.           Swing is a set of rich platform-independent graphical components.
  1542.           It also introduced the Collections library, and Java 2D.
  1543.  
  1544.  11. (Sect. 4) What is the difference between jre and java?
  1545.  
  1546.      [*] They are functionally equivalent, with minor differences in the
  1547.      handling of default classpath and options supported. To reduce
  1548.      confusion, the jre command was removed in JDK 1.2. Instead there is a
  1549.      "java" command in both bin and jre/bin.
  1550.  
  1551.      jre.exe is the java launcher that comes with the Java Runtime
  1552.      Environment. It ignores the CLASSPATH environment setting in favor of
  1553.      its own internally generated default and whatever is supplied on the
  1554.      cmd line using -cp or -classpath. It's intended to be a bit simpler for
  1555.      those who are only ever running Java programs, not developing them.
  1556.  
  1557.      java.exe is the java launcher that comes with the JDK. It uses the
  1558.      CLASSPATH environment setting as a starting point and then tacks on its
  1559.      own internally generated entries.
  1560.  
  1561.      They both serve the same purpose and that's to start a Java VM, have it
  1562.      run a Java application, then terminate. The source for jre.exe is
  1563.      provided in the JDK. The source to java.exe is provided only in the JDK
  1564.      Source distribution.
  1565.  
  1566.  12. (Sect. 4) What IDEs (Integrated Development Environments) are there?
  1567.  
  1568.      [*] Some popular IDEs include: (... if you have info on the platforms
  1569.      that each of these support, send it in, and I'll add it to the FAQ).
  1570.       Apptivity (Progress)   http://www.apptivity.com
  1571.       Blue J (free)          http://www.sd.monash.edu.au/bluej
  1572.       Bluette (free)         http://www.bluette.com
  1573.       Chicory (free)         http://www.chicory.com
  1574.       CodeWarrior
  1575.       Professional           http://www.metrowerks.com
  1576.       Freebuilder (free)     http://www.freebuilder.org
  1577.       GRASP (free)           http://www.eng.auburn.edu/grasp
  1578.       Grinder                http://www.tpex.com
  1579.       Java WorkShop (Sun)    http://www.sun.com/workshop/java
  1580.       Javelin, Visual Object
  1581.       Development for Java   http://www.stepahead.com.au
  1582.       JBuilder (Inprise)     http://www.inprise.com/jbuilder
  1583.       JDE for emacs          http://sunsite.auc.dk/jde/
  1584.       Jirvana (free)         http://www.jirvana.com/Jirvana/Jirvana.html
  1585.       JPadPro                http://www.modelworks.com
  1586.       Kawa (Webcetera)       http://www.tek-tools.com/kawa
  1587.       Metamata               http://www.metamata.com
  1588.       NetBeans (Swing-based) http://www.netbeans.com
  1589.       PARTS alpha
  1590.       (ObjectShare)          http://www.objectshare.com
  1591.       PowerJ (Sybase)        http://www.sybase.com/products/powerj
  1592.       SilverStream           http://www.silverstream.com
  1593.       Simplicity for Java    http://www.datarepresentations.com
  1594.       Super Mojo (Penumbra)  http://www.penumbrasoftware.com
  1595.       SuperCede (Asymetrix)  http://www.supercede.com
  1596.       teikade (PFU Ltd)      http://www.pfu.co.jp/teikade
  1597.       Together/J (Object Intl
  1598.       Inc.)                  http://www.oi.com
  1599.       Visaj (Imperial SW
  1600.       Tech)                  http://www.imperial-software-tech.co.uk
  1601.       VisualAge (IBM)        http://www.software.ibm.com/ad/vajava
  1602.       Visual Cafe (Symantec) http://cafe.symantec.com
  1603.  
  1604.       Visual J++ (Microsoft) http://msdn.microsoft.com/visualj/default.asp
  1605.                              (not recommended)
  1606.       Xelfi 0.94             http://www.xelfi.com
  1607.  
  1608.  13. (Sect. 4) Why is Visual J++ not recommended?
  1609.  
  1610.      Because Microsoft's strategic objective is "Kill cross-platform Java"
  1611.  
  1612.      [*] It is not in Microsoft's financial interest to allow users to
  1613.      easily move software to different platforms. Microsoft is the only
  1614.      company in the computer industry that is actively trying to undermine
  1615.      Java. This is not speculation -- the Department of Justice's lawsuit
  1616.      quoted a Microsoft memo describing the strategic objective to "kill
  1617.      cross-platform Java by grow[ing] the polluted Java market". See
  1618.      http://www.usdoj.gov/atr/cases/f1700/1762.htm
  1619.      VJ++ can be used in a compatible way, but the tool encourages use of
  1620.      Windows lock-ins. The J++ compiler introduced new keywords and other
  1621.      deliberate incompatibilities.
  1622.  
  1623.      Microsoft is being sued because of unauthorized changes it made in
  1624.      Java. A federal judge issued a preliminary injunction against Microsoft
  1625.      in March 1998, prohibiting them from labelling their incompatible J++
  1626.      product as Java. Another injunction was issued against Microsoft in Nov
  1627.      1998, requiring them to remove some deliberate incompatibilities with
  1628.      standard Java. (Recall that Microsoft did not create Java, but
  1629.      contracted with Sun to distribute it).
  1630.  
  1631.      Microsoft is in a real jam over Java; it contracted with Sun to
  1632.      distribute standard Java, and then made many changes to its product
  1633.      to make it deliberately non-portable. Sun sued Microsoft to enforce the
  1634.      contract, and the preliminary legal decisions have been in Sun's favor.
  1635.      Some analysts speculate that Microsoft will leave its customers in the
  1636.      lurch and cancel VJ++. See
  1637.      http://cnn.com/TECH/computing/9903/23/javajam.idg/index.html
  1638.  
  1639.      Speak to your management chain - how comfortable do they feel using a
  1640.      Microsoft product that is embroiled in a legal dispute, that introduces
  1641.      deliberate incompatibilities, and whose stated goal is to lock you in
  1642.      to one platform? It is a safer choice to get standard Java from any
  1643.      other source than Microsoft. You can use these facts to move your
  1644.      company to standard Java.
  1645.  
  1646.      As a Java programmer please join the Java Lobby, an independent
  1647.      organization dedicated to representing independent non-vendor interests
  1648.      in Java. It's free, and you can sign up by visiting
  1649.      http://www.javalobby.org for details. Other ways to encourage portable
  1650.      java:
  1651.         o Use development environments from other vendors, or convert
  1652.           Microsoft Visual J++ to use Sun's JDK, following the instructions
  1653.           at http://www.orbiter.demon.co.uk/
  1654.         o Use Netscape Communicator (not Internet Explorer)
  1655.         o If required to use Internet Explorer, use the Java Plug-In to get
  1656.           a standard Java system inside it.
  1657.         o Use a standard JVM from GNU, Kaffe, any of the IDE vendors, or Sun
  1658.           (but not Microsoft's J++ SDK)
  1659.  
  1660.         o Free standard Java compilers and the Java Plug-In can be
  1661.           downloaded from http://java.sun.com.
  1662.         o Free standard Java Virtual Machines can be downloaded from
  1663.           http://www.kaffe.org, http://www.oryxsoft.com/projects/gvm, and
  1664.           http://www.redhat.com/linux-info/jolt
  1665.         o Free Java AWT software can be downloaded from
  1666.           http://www.biss-net.com/biss-awt.html and the files are all at
  1667.           ftp.java-linux.org (the linux site) too.
  1668.         o Free Java software can be downloaded from
  1669.           http://www.gnu.org/software/java/java.html
  1670.  
  1671.      Just for the record, the May 1998 federal case against Microsoft has
  1672.      nothing to do with innovation or product design, as Microsoft
  1673.      frequently insists. Microsoft is actually charged with
  1674.         o taking anti-competitive action to exclude competition in browsers,
  1675.           in order to protect its monopoly in desktop operating systems.
  1676.         o using its monopoly to impose restrictive agreements that require
  1677.           PC manufacturers to accept the Microsoft browser with Windows, and
  1678.           that hinder the promotion of competing browsers.
  1679.      Many people think that contracts between "A" and "B",
  1680.      restricting/discouraging "B" from distributing "C's" products are
  1681.      sleazy. ["A" is Microsoft, "B" is AOL, many ISPs, computer vendors,
  1682.      etc. "C" is Netscape"]. Such contracts are in restraint of competition
  1683.      and illegal when used by a monopoly. This is why Microsoft is facing
  1684.      mounting legal problems in the United States, Italy, Brazil, and the
  1685.      European Union.
  1686.  
  1687.  14. (Sect. 4) What language is the Java compiler and JVM written in?
  1688.  
  1689.      [*] Sun's javac Java compiler is written in Java.
  1690.      Sun's java JVM interpreter is written in Java with some C, C++ for
  1691.      platform-specific and low level routines.
  1692.      Sun's Java Web Server is written in Java.
  1693.  
  1694.      Other companies have chosen other approaches. IBM's Jikes compiler
  1695.      (which is praised for its speed) is written in C++, but of course each
  1696.      version only runs on one platform. Jikes versions have been prepared
  1697.      for IBM AIX, Linux Intel (glibc), Win95/NT and Solaris Sparc at
  1698.      http://www.alphaworks.ibm.com/formula/jikes.
  1699.  
  1700.  15. (Sect. 4) How do I turn off the JIT in the JDK?
  1701.  
  1702.      [*] The command that works in both JDK 1.1.6 on, and JDK 1.2/2 is
  1703.  
  1704.               java -Djava.compiler=NONE   ...
  1705.  
  1706.  
  1707.          One reason for turning off the JIT is to get more
  1708.          information about any exception that is thrown in your code.
  1709.          But HotSpot is able to produce line numbers in stack traces
  1710.          even for JIT'd code.  HotSpot rocks.
  1711.  
  1712.  16. (Sect. 4)
  1713.      How can I store the errors from the javac compiler in a DOS file?
  1714.  
  1715.      javac foo.java > errorfile doesn't work.
  1716.      [*]
  1717.          javac writes errors to stderr,
  1718.          The problem is that DOS doesn't allow stderr to be redirected
  1719.          (as command.com is very poor software).  So you
  1720.          have to use a special error redirection mechanism in the compiler:
  1721.  
  1722.  
  1723.          javac -J-Djavac.pipe.output=true myfile.java > errors.txt
  1724.  
  1725.  
  1726.          In JDK 1.2, you can use:
  1727.          javac -Xstdout
  1728.  
  1729.          You typically use this when a compilation produces a lot of error messages,
  1730.          and they scroll off the DOS window before you can read them.
  1731.  
  1732.  
  1733.          Alternatively,
  1734.          you can get a scollbar to appear on a DOS window by changing the properties
  1735.          with the "Layout" tab. Change the Screen Buffer Size Height: to some
  1736.          multiple > 1 of the Window Size Height. E.g. use a buffer height of 100 and
  1737.          screen height of 25 (the default). This will give you three buffers of
  1738.          scroll "history."
  1739.  
  1740.  
  1741.           The DOS limitation is improved in NT, where you can write
  1742.  
  1743.  
  1744.          javac myfile.java 2> errors.dat
  1745.  
  1746.  
  1747.  17. (Sect. 4)
  1748.      How can I pretty-print Java source?
  1749.      [*]
  1750.          For tools that reformat code, try:
  1751.  
  1752.  
  1753.  
  1754.  
  1755.  
  1756.         o
  1757.  
  1758.                            http://www.parallax.co.uk/~rolf/download/jpp.pl
  1759.  
  1760.         o
  1761.  
  1762.                             http://www.bigfoot.com/~davidsont/jstyle
  1763.  
  1764.         o
  1765.  
  1766.                            http://www.mmsindia.com/JPretty.html
  1767.  
  1768.         o
  1769.  
  1770.               http://www.almide.demon.co.uk/source_code/java/JavaCC/Pretty/Pretty.html
  1771.  
  1772.         o
  1773.  
  1774.                            http://www.geocities.com/~starkville
  1775.  
  1776.  
  1777.  
  1778.  
  1779.          For tools that print code neatly, try:
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.         o
  1786.  
  1787.                            http://www.eng.auburn.edu/department/cse/research/grasp/
  1788.  
  1789.  
  1790.          Some Unix utilities work adequately:
  1791.  
  1792.  
  1793.  
  1794.         o
  1795.                   cb (very few style choices though)
  1796.  
  1797.         o
  1798.                   alias printjava 'vgrind -lC++ -t -w \!* | lp' works pretty well too.
  1799.  
  1800.  
  1801.          Perhaps the best tools are the GNU utilities. Use enscript to
  1802.          generate postscript files with Java-specific formatting. Then use
  1803.          GhostScript/GhostView to preview and print the files to a
  1804.          non-PostScript printer, if necessary. The scripts can be found at:
  1805.  
  1806.  
  1807.  
  1808.         o
  1809.                   GNU Enscript - pretty
  1810.                   printer and PostScript formatter
  1811.  
  1812.         o
  1813.                   Ghostscript, Ghostview, and
  1814.                   GSView for Unix
  1815.  
  1816.         o gsv25w32.zip
  1817.                    - GSView for NT (requires the following Ghostscript files)
  1818.  
  1819.         o
  1820.  
  1821.                   gs510ini.zip - Ghostscript configuration, initialization, and
  1822.                   example files
  1823.  
  1824.         o
  1825.  
  1826.                   gs510w32.zip - Ghostscript core binaries for Windows NT
  1827.  
  1828.         o
  1829.  
  1830.                   gs510fn1.zip - Ghostscript standard fonts
  1831.  
  1832.  
  1833.                        -------------------------------
  1834.  
  1835. 5. Compiler Messages
  1836.  
  1837.  
  1838.      Most of the "questions" in this section are diagnostic messages from the
  1839.      compiler.  Each answer explains what the message means, and how to avoid it.
  1840.  
  1841.   1. (Sect. 5)
  1842.       Why did I get an OutOfMemory error when porting working code from
  1843.      JDK 1.0.2 to 1.1?
  1844.      [*]
  1845.          The preset memory limit has changed. It went down to 16MB so as not to
  1846.          penalize low memory machines. You can adjust it with
  1847.  
  1848.           java -mx128m Frotz        # jdk 1.1
  1849.           java -Xmx128m Frotz       # jdk 1.2
  1850.  
  1851.  
  1852.      to get a 128MB extent.
  1853.  
  1854.      Also see the Runtime methods freeMemory() and totalMemory().
  1855.  
  1856.   2. (Sect. 5) Why do I get a "Statement not reached" error from javac for
  1857.      no apparent reason?
  1858.  
  1859.      [*] JDK 1.0 has a limit of 63 words of storage for local variables in
  1860.      any method. longs and doubles require two words of storage, and all
  1861.      other primitive types and all reference types require one word. If you
  1862.      assign values to more than 63 words of local variables, you will get a
  1863.      "Statement not reached" error on the statement after you assign to the
  1864.      variable that contains the 64th word. In JDK 1.1, the low limit was
  1865.      removed.
  1866.  
  1867.   3. (Sect. 5) class MyOrdinaryClass must be declared abstract.
  1868.      It does not define void actionPerformed(java.awt.event.ActionEvent)
  1869.  
  1870.      [*] This is one of those error messages where the compiler tries to
  1871.      guess what you meant, and gives you a message based on a wrong guess!
  1872.      So the message is confusing.
  1873.  
  1874.      Your MyOrdinaryClass class implements ActionListener, which means you
  1875.      must include a definition of the methods from the ActionListener
  1876.      interface.
  1877.  
  1878.      But you did not. You either left a method out, or (more likely) you
  1879.      misspelled its name. Perhaps you wrote "ActionListener" instead of
  1880.      "actionListener".
  1881.  
  1882.      So the compiler did not find the method to fulfill the interface. Since
  1883.      there was a method promised but not supplied, the compiler thinks you
  1884.      were aiming at an abstract class, and it prints an error message
  1885.      accordingly.
  1886.  
  1887.   4. (Sect. 5) Variable may not have been initialized.
  1888.  
  1889.          URL test;
  1890.          try {
  1891.           test = new URL("http://osprey.avs.dec.com");
  1892.          } catch (MalformedURLException e) {
  1893.           System.out.println("bad URL:" + e.getMessage());
  1894.          }
  1895.          System.out.println("this is url " + test);
  1896.  
  1897.  
  1898.      [*] The compiler will warn you if you use a variable before it is
  1899.      certain to have been initialized (not just with the default value)
  1900.      since this means you probably forgot to set it.
  1901.  
  1902.      In the case of exceptions, you have to consider that the flow of
  1903.      control may terminate abruptly, with no operations completed. In the
  1904.      example above, if an exception is raised in the try clause, variable
  1905.      test will not be assigned a value, yet you are using it after the catch
  1906.      clause. One solution would be to declare test with an explicit initial
  1907.      value of null, but this works only because toString() works on a null
  1908.      reference. (toString() is invoked implicitly by operator + with String
  1909.      operand.)
  1910.  
  1911.      Always initialize to a value that will work notwithstanding exceptions
  1912.      being thrown.
  1913.  
  1914.   5. (Sect. 5) No constructor {superclass}()
  1915.      I extended the class called Frotz, and the compiler is giving me an
  1916.      error message "No constructor Frotz()" in the child class. Why?
  1917.  
  1918.      [*] When you define a constructor for a class, the compiler inserts a
  1919.      call to the superclass' parameterless constructor unless you explicitly
  1920.      call the superclass' constructor at the start of your constructor. If
  1921.      the superclass doesn't *have* a parameterless constructor, the compiler
  1922.      emits a message to that effect. The solution is usually to call the
  1923.      superclass' constructor at the start of your constructor.
  1924.  
  1925.   6. (Sect. 5) No constructor matching MyCheckbox(myApplet)
  1926.  
  1927.          MyApplet.java:11: No constructor matching MyCheckbox(myApplet)
  1928.          found in class MyCheckbox.
  1929.  
  1930.          bp1 = new MyCheckbox(this);
  1931.          ^
  1932.  
  1933.      [*] If a compiler isn't finding a constructor you thought you created,
  1934.      check whether you gave a return value to the method (remember,
  1935.      constructors have no return value). E.g.,
  1936.  
  1937.          public void MyCheckbox( Container parent )
  1938.  
  1939.  
  1940.      If you did, the compiler will think it is an ordinary method, not a
  1941.      constructor. This is a common mistake and hard to spot.
  1942.  
  1943.   7. (Sect. 5) Type expected {public method variable}
  1944.  
  1945.          public static void main(String[] args) {
  1946.          ^
  1947.          Statement expected.
  1948.          public static final float Conversion_Factor = 39.37;
  1949.          ^
  1950.          Type expected.
  1951.  
  1952.      [*] Argument and variable declarations inside methods are never public
  1953.      or static because they are local to a method. (Before JDK 1.1 they
  1954.      couldn't be final either, but there was no good reason for that
  1955.      restriction and it was dropped.) If you have public or static
  1956.      variables, move them outside the method. They are usually put at the
  1957.      beginning of the class.
  1958.  
  1959.   8. (Sect. 5) Can't access protected method clone in class java.lang.Object
  1960.  
  1961.          T.java:96: Can't access protected method clone in
  1962.          class java.lang.Object. OtherT is not a subclass of
  1963.          the current class.
  1964.  
  1965.      [*] Object.clone() is protected because subclasses might want to
  1966.      restrict access to cloning, and if Object.clone() were declared public,
  1967.      subclasses could never make it more restrictive. The subclass can make
  1968.      access to the clone() operation less restrictive.
  1969.      This means that a method can clone its own objects, but a method cannot
  1970.      clone objects of another class, unless you do something like:
  1971.  
  1972.          class SomeObject implements Cloneable {
  1973.              public Object clone()
  1974.                  throws CloneNotSupportedException {
  1975.                  return super.clone();
  1976.              }
  1977.          }
  1978.  
  1979.  
  1980.      i.e., override clone() to make it public, and call the superclass
  1981.      clone().
  1982.  
  1983.          class Foo {
  1984.           Bar bar;
  1985.           Foo (Bar b) {
  1986.               try {bar = (Bar) b.clone();}
  1987.               catch (Exception e) {}
  1988.           }
  1989.          ...
  1990.          class Bar implements Cloneable {
  1991.           public Object clone()
  1992.               throws java.lang.CloneNotSupportedException {
  1993.               return super.clone();
  1994.           }
  1995.          }
  1996.  
  1997.  
  1998.      Another refinement is to note that Object.clone() only throws a
  1999.      CloneNotSupportedException when the object doesn't implement Cloneable.
  2000.      Since you control what your classes do and don't implement, you can
  2001.      ensure that Cloneable classes implement the interface, and you don't
  2002.      need to make the overridden clone() throw the exception.
  2003.  
  2004.          public class X implements Cloneable {
  2005.              public Object clone() { // no throws
  2006.                  try {
  2007.                            // in case members need cloning
  2008.                      X c = (X)super.clone();
  2009.                      return c;
  2010.                     } catch (CloneNotSupportedException e) {
  2011.                     // should not happen, because of Cloneable
  2012.                         throw new InternalError();
  2013.                     }
  2014.                 }
  2015.          }
  2016.  
  2017.  
  2018.   9. (Sect. 5) Deprecated methods
  2019.      What does "deprecated" mean? I got this in a compiler error message.
  2020.  
  2021.      [*] "Deprecated" means you are using an older API, that Sun has
  2022.      replaced with a newer one (usually to follow more consistent naming
  2023.      conventions). Deprecated methods are not recommended for use. They are
  2024.      supported in the short term, but your code should be updated with the
  2025.      new. To update your code, compile your old code using javac's
  2026.      "-deprecation" option to list deprecated methods, then find the
  2027.      replacement methods in the current HTML API documentation for the old
  2028.      deprecated methods.
  2029.      As an example of a deprecated API, Component.size() was replaced by
  2030.      Component.getSize().
  2031.  
  2032.      See also
  2033.      http://java.sun.com/products/jdk/1.1/docs/guide/
  2034.      misc/deprecation/index.html, "1.1 Deprecated Methods"
  2035.      and
  2036.      http://java.sun.com/products/jdk/1.1/docs/guide/
  2037.      awt/DeprecatedMethods.html, "Deprecated methods in the 1.1 AWT"
  2038.  
  2039.  10. (Sect. 5) double y = sin(90);
  2040.      What's wrong? That code provokes compiler messages.
  2041.  
  2042.      [*] You need to write it this way:
  2043.  
  2044.          double cvtDegToRad = Math.PI/180;
  2045.          double x = 90*cvtDegToRad;
  2046.          double y = Math.sin(x);
  2047.  
  2048.  
  2049.      sin is a static method of the Math class that takes radians. You need
  2050.      to use the "Math" classname, e.g. Math.sin instead of plain sin,
  2051.      because you have to say what class or object these methods belong to.
  2052.  
  2053.      A very common mistake is to assume that importing a class means that
  2054.      you don't have to qualify the names of its members. When you call a
  2055.      method you have to state the name of the class or object it belongs to,
  2056.      regardless of any imports you have done. (Except inside the class
  2057.      itself, obviously).
  2058.  
  2059.      The trig functions are static methods of the Math class, so you give
  2060.      the name of the class in invoking them. Further, the Math class works
  2061.      in radians, not degrees. 360 degrees = 2 pi radians, so use a
  2062.      conversion factor as shown if you are working with degrees.
  2063.  
  2064.  11. (Sect. 5) Can't make static reference to method...
  2065.  
  2066.      [*] Your code probably looks something like this:
  2067.  
  2068.          class myclass {
  2069.              public static void main(String args[]) {
  2070.                myMethod();
  2071.              }
  2072.              public void myMethod() { //some code
  2073.              }
  2074.          }
  2075.  
  2076.  
  2077.      Static (class) methods can only call without qualification other static
  2078.      methods, so you either have to qualify the call in (static) main() to
  2079.      (nonstatic) myMethod() with an object of type myclass, or you have to
  2080.      make myMethod() static.
  2081.  
  2082.      People often forget that even though main is "in" myclass, there is no
  2083.      implicit object when you are in main() because it is static. This
  2084.      happens especially when writing code to run an applet as an
  2085.      application, where you want to call init() and start() from main.
  2086.  
  2087.          public static void main(String[] args) {
  2088.              Applet ma = new myApplet(); // have to create object
  2089.              ma.init();  // use to qualify access to non-static methods
  2090.              ma.start();
  2091.          }
  2092.  
  2093.  
  2094.  12. (Sect. 5) Incompatible type for =. Explicit cast needed...
  2095.  
  2096.          byte b = 0;
  2097.          Incompatible type for =.
  2098.          Explicit cast needed to convert int to byte.
  2099.          b = b + 100;    // compiler error message
  2100.          b += 100;       // works OK
  2101.  
  2102.  
  2103.      [*] Arithmetic expressions are promoted to the type of the longest,
  2104.      floatiest operand in them, or at least to int. The first statement
  2105.      involves the assignment of an expression. The expression is promoted to
  2106.      32 bits, and must be cast back down to 8 bits, like this: b = (byte)
  2107.      (b+100); The second is an operator assignment, and the cast back to
  2108.      byte takes place automatically. The Java Language Specification says
  2109.      that a compound assignment expression of the form E1 op= E2 is
  2110.      equivalent to E1 = (typecast)((E1) op (E2)), where "typecast" is the
  2111.      type of E1, except that E1 is evaluated only once. (See JLS 15.25.2
  2112.      Compound Assignment Operators) The compile-time narrowing of constants
  2113.      means that code such as:
  2114.  
  2115.          byte theAnswer = 42;
  2116.  
  2117.  
  2118.      is allowed, with no cast necessary. (See JLS 5.2 Assignment Conversion)
  2119.  
  2120.      Other sites:
  2121.      JLS 5.2 Assignment Conversion
  2122.      JLS 15.25.2 Compound Assignment Operators
  2123.  
  2124.  13. (Sect. 5) Class {package}.{class} not found in type declaration.
  2125.      I am trying to compile file "{class2}.java" in a package, and I get
  2126.      this compiler error. {class2}.java refers to {package}.{class}, but the
  2127.      file {class}.java and {class2}.java are in the same {package}
  2128.      directory, which is the current directory and which is in the CLASSPATH
  2129.      variable. Both files have "package {package};" at the top of the file.
  2130.      What's the problem?
  2131.  
  2132.      [*] When the source refers to classes in packages, the CLASSPATH has to
  2133.      point to the root of the package/directory hierarchy for a reference to
  2134.      resolve correctly. This is true even for source files in the same
  2135.      package (and directory). I.e., assuming {class} and {class2} are both
  2136.      in {package}, {class} can't make a reference to {class2} unless the
  2137.      CLASSPATH is set so javac can find {package}/{class2}.java. It should
  2138.      make no difference what directory you are in when you invoke javac,
  2139.      unless you are relying on "." in the CLASSPATH to point to the package
  2140.      root or are specifying the source file with a relative path (e.g.,
  2141.      {package}/{class}.java).
  2142.  
  2143.      Some examples, assuming
  2144.         o - Foo.java and Bar.java are in /java/source/pack/
  2145.         o - Both have "package pack;" as the first statement
  2146.         o - Foo.java includes "Bar b = new Bar();"
  2147.  
  2148.          # solaris ksh
  2149.          $ alias jc=/java/jdk11/bin/javac
  2150.          $ CLASSPATH=/java/source/
  2151.          $ jc /java/source/pack/*.java  # works fine
  2152.          $ cd /java/source/pack
  2153.          $ CLASSPATH=.
  2154.          $ jc *.java         # fails - Foo.java can't find class Bar
  2155.          $ cd ..             # now . is package root, /java/source/
  2156.          $ jc pack/*.java    # works
  2157.  
  2158.  
  2159.  14. (Sect. 5) public class "Foo" must be defined in "Foo.java"
  2160.      I get this message even though it is in Foo.java. What gives?
  2161.  
  2162.      [*] Javac verifies that a public class is defined in a file of the same
  2163.      name (e.g., that public class Foo is defined in Foo.java). Two things
  2164.      you can check:
  2165.  
  2166.      First, make sure the case matches exactly. public class Foo cannot be
  2167.      in foo.java; it has to be in Foo.java.
  2168.  
  2169.      Second, are you using MKS on win32? Javac on win32 assumes you are
  2170.      using the DOS path separator (\) even though MKS accepts the Unix path
  2171.      separator (/). When javac tries to parse a your Unix-style path, it
  2172.      won't produce the correct filename, the match will fail, and it will
  2173.      emit an error. You have to use the DOS path separator (\), which must
  2174.      be escaped in MKS - e.g., "javac H:\\source\\package\\Foo.java".
  2175.      Alternatively, you can traverse to each source directory and avoid
  2176.      pathnames altogether.
  2177.  
  2178.                        -------------------------------
  2179.  
  2180. 6. Java Language Issues
  2181.  
  2182.      How-to
  2183.  
  2184.   1. (Sect 6.) How do I compare two Strings?
  2185.  
  2186.      if (s1 == s2)
  2187.  
  2188.      is giving me funny results.
  2189.  
  2190.      [*] The comparison using "==" on objects, such as Strings, is asking,
  2191.      "Do these two objects have the same reference?" Do they have the same
  2192.      address, and hence are the same object? What you really want to do is
  2193.      ask, "Do these two Strings have the same *contents*?"
  2194.      Compare String contents with any of the following:
  2195.  
  2196.          if (s1.equals(s2) )
  2197.          if (s1.equalsIgnoreCase(s2) )
  2198.          if (s1.startsWith(s2) )
  2199.          if (s1.endsWith(s2) )
  2200.          if (s1.regionMatches(s1_offset, s2, s2_offset, length) )
  2201.          if (s1.compareTo(s2) < 0)
  2202.  
  2203.  
  2204.      (There are other ways, too.)
  2205.      Note that you can do this with literals:
  2206.  
  2207.      if ("apple".equals(s2) ) ...
  2208.  
  2209.  
  2210.      If you compare these the other way round, like this:
  2211.  
  2212.      if ( s2.equals("apple") ) ...
  2213.  
  2214.  
  2215.      and s2 is null, you will get a null pointer exception.
  2216.  
  2217.   2. (Sect. 6) How do you get the code value of a char?
  2218.      I would like to transform a char into the corresponding int value, that
  2219.      represents the code value of the char. How?
  2220.  
  2221.      [*] Like this.
  2222.  
  2223.          char c = 'A';
  2224.          int i = c;
  2225.  
  2226.  
  2227.      Going the other way is just
  2228.  
  2229.          c = (char) i;
  2230.  
  2231.  
  2232.      This question crops up so frequently because the BASIC language uses
  2233.      functions to map characters into ints, ASC( 'A' ) => 65 causing BASIC
  2234.      programmers to seek the corresponding Java functions. The same is true
  2235.      for Pascal, Ada, and other languages.
  2236.  
  2237.   3. (Sect. 6) Why does b >>>= 1 give me the same result as b >>= 1?
  2238.  
  2239.      [*] ">>" is a "signed" or "arithmetic" shift, namely, it replicates the
  2240.      sign bit on the left as it shifts.
  2241.      The ">>>" operator is an "unsigned" or "logical" shift; it does a shift
  2242.      right and zero fill. However, ">>>" looks like it does a signed shift
  2243.      with negative bytes and shorts, where int promotion alters the sign.
  2244.  
  2245.      This occurs when you have a non-canonical type, byte, or short, with a
  2246.      negative value, e.g.
  2247.  
  2248.          byte b = -15; // 0xf1
  2249.          b = (byte) b >>> 4; // why isn't b 0x0f ?
  2250.  
  2251.  
  2252.      The initial expectation is that an unsigned shift right of 0xf1 would
  2253.      successively be (in binary)
  2254.  
  2255.          0111_1000 then
  2256.          0011_1100 then
  2257.          0001_1110 then
  2258.          0000_1111
  2259.  
  2260.  
  2261.      But that doesn't happen. The rules of arithmetic in Java say that all
  2262.      operands are converted at least to int before the operation (and
  2263.      possibly to a more capacious type). That means our byte is promoted to
  2264.      an int, so instead of shifting 0xf1, we are shifting 0xfffffff1. If you
  2265.      shift right unsigned 4 places, you get 0x0fffffff. When you cast that
  2266.      to a byte it becomes 0xff, or -1.
  2267.  
  2268.      The bottom line is that the final result is the same as if you had
  2269.      performed the signed shift because the unsigned shift applied to the
  2270.      intermediate int, not to the original byte. This anomaly means that
  2271.      ">>>" is useless for negative bytes and shorts. It is probably safer
  2272.      and clearer not to use it at all, but to mask and shift instead:
  2273.  
  2274.          // not recommended
  2275.          byte b = -15;
  2276.          b = (byte) (b>>>4);
  2277.          System.out.println("b= "+Integer.toHexString(b) );
  2278.          // recommended
  2279.          b = -15;
  2280.          b = (byte) ( (b & 0xFF) >> 4 );
  2281.          System.out.println("b= "+Integer.toHexString(b) );
  2282.  
  2283.  
  2284.   4. (Sect. 6) Why does the <unexpected> happen in floating point?
  2285.  
  2286.      [*] There are several unexpected things that seem to bite programmers
  2287.      with floating point. This is almost always a result of the programmer
  2288.      not being fully conversant with floating point arithmetic in general,
  2289.      rather than a problem relating to Java.
  2290.  
  2291.      The question of floating point accuracy comes up with Java more than
  2292.      with C++ (for example) because of Java's decision in the println()
  2293.      method to print enough digits to distinguish the number from the
  2294.      next-closest number, rather than rounding it to 6 significant digits by
  2295.      default as the C/C++ libraries do. [ISO C, Sect 7.9.6.1, line 21 of
  2296.      "the double argument"]
  2297.  
  2298.      If you seem to be having problems with floating point, the problem
  2299.      probably stems from the fact that floating-point arithmetic is
  2300.      inherently imprecise. You can expect up to 7 digits of precision with
  2301.      floats and 16 digits with doubles. However, that does not mean that a
  2302.      number that can be exactly represented in 7 digits decimal or can be
  2303.      exactly represented as a binary floating point number. On the contrary,
  2304.      that is usually not the case.
  2305.  
  2306.      Additionally, when Java converts floating point numbers to a String, as
  2307.      is done when they are output, enough digits are printed so the number
  2308.      can be read back in with no loss of precision. For this reason, you may
  2309.      see more "inaccuracies" in floating point output than you are used to.
  2310.      You are actually getting more accuracy than on systems (like C,C++)
  2311.      that suppress the less significant digits.
  2312.  
  2313.      For more information and detailed specifications on how Java deals with
  2314.      floating point, see the URLs listed below.
  2315.  
  2316.      Other sites:
  2317.      What Every Computer Scientist Should Know About Floating Point.
  2318.      http://java.sun.com/products/jdk/1.1/compatibility.html#incompatibilities
  2319.  
  2320.      JLS 4.2.3 Floating-Point Types and Values
  2321.      JLS 4.2.4 Floating-Point Operations
  2322.      JLS 3.10.2 Floating-Point Literals
  2323.      JLS 5.2.3 Narrowing Primitive Conversions
  2324.      http://gams.nist.gov/javanumerics/jgfnwg-01.html
  2325.      See also "the guff from Hough" at http://www.validgh.com/java
  2326.  
  2327.      If you want the rounded floating point output that most languages have,
  2328.      use the new java.text package of Java 1.1 to limit the number of digits
  2329.      that are output. If you need more precision than about 16 digits, use
  2330.      the BigInteger and BigDecimal classes of Java 1.1.
  2331.  
  2332.      Understanding the Java Language
  2333.  
  2334.   5. (Sect. 6) How can I program linked lists if Java doesn't have pointers?
  2335.  
  2336.      [*] Of all the misconceptions about Java, this is the most egregious.
  2337.      Far from not having pointers, in Java, object-oriented programming is
  2338.      conducted exclusively with pointers. In other words, objects are only
  2339.      ever accessed through pointers, never directly. The pointers are termed
  2340.      "references" and they are automatically dereferenced for you.
  2341.  
  2342.      Java does not have pointer arithmetic or untyped casting. By removing
  2343.      the ability for programmers to create and modify pointers in arbitrary
  2344.      ways, Java makes memory management more reliable, while still allowing
  2345.      dynamic data structures. Also note that Java has NullPointerException,
  2346.      not NullReferenceException.
  2347.  
  2348.      A linked list class in Java might start like this:
  2349.  
  2350.          public class LinkedList {
  2351.              public LinkedList head;
  2352.              public LinkedList next;
  2353.              public Object data;
  2354.              public LinkedList advanceToNext(LinkedList current) { ...
  2355.          }
  2356.  
  2357.  
  2358.      Another choice for a linked list structure is to use the built-in class
  2359.      java.util.Vector which accepts and stores arbitrary amounts of Object
  2360.      data (as a linked list does), and retrieves it by index number on
  2361.      demand (as an array does). It grows automatically as needed to
  2362.      accommodate more elements. Insertion at the front of a Vector is a slow
  2363.      operation compared with insertion in a linked list, but retrieval is
  2364.      fast. Which is more important in the application you have?
  2365.  
  2366.   6. (Sect. 6) Are parameters in Java passed by value or by reference?
  2367.  
  2368.      [*] All parameters (values of primitive types and values that are
  2369.      references to objects) are passed by value. However this does not tell
  2370.      the whole story, since objects are always manipulated through reference
  2371.      variables in Java. Thus one can equally say that objects are passed by
  2372.      reference (and the reference variable is passed by value). This is a
  2373.      consequence of the fact that variables do not take on the values of
  2374.      "objects" but values of "references to objects" as described in the
  2375.      previous question on linked lists.
  2376.  
  2377.      Bottom line: The caller's copy of primitive type arguments (int, char,
  2378.      etc.) _do not_ change when the corresponding parameter is changed.
  2379.      However, the fields of the caller's object _do_ change when the called
  2380.      method changes the corresponding fields of the object (reference)
  2381.      passed as a parameter.
  2382.  
  2383.      Also in this FAQ:
  2384.      How can I program linked lists if Java doesn't have pointers?
  2385.      Other sites:
  2386.      JLS 8.4.1 Formal Parameters
  2387.  
  2388.   7. (Sect. 6) What are "class literals"?
  2389.  
  2390.      [*] A feature introduced in JDK 1.1. They are literals of type "Class"
  2391.      that hold a value representing any class. There are even values to
  2392.      represent "void" and an array, like this:
  2393.  
  2394.          Class myCl1 = Character.class;
  2395.          Class myCl2 = Void.class;
  2396.          Class myCl3 = Object.class;
  2397.          Class myCl4 = String[].class;
  2398.          Class myCl5 = int[][].class;
  2399.  
  2400.  
  2401.      You might use it like this:
  2402.  
  2403.          Class cl = thing.getClass();
  2404.          if (cl.equals(myCl1))
  2405.          System.out.println("It's a Character class");
  2406.  
  2407.  
  2408.      Note that a class literal
  2409.  
  2410.              Component.class
  2411.  
  2412.  
  2413.      is the equivalent of
  2414.  
  2415.              Class.forName("java.awt.Component")
  2416.  
  2417.  
  2418.      The second can throw an exception, but the first cannot. If you don't
  2419.      know the name of the class when you write the code, you cannot use the
  2420.      first form.
  2421.  
  2422.   8. (Sect. 6) What are the naming conventions in Java?
  2423.  
  2424.      [*] The naming conventions are straightforward:
  2425.        1. Package names are guaranteed uniqueness by using the Internet
  2426.           domain name in reverse order: com.javasoft.jag - the "com" or
  2427.           "edu" (etc.) part used to be in upper case, but now lower case is
  2428.           the recommendation.
  2429.        2. Class and interface names are descriptive nouns, with the first
  2430.           letter of each word capitalized: PolarCoords. Interfaces are often
  2431.           (not always) called "something-able", e.g. "Runnable", "Sortable".
  2432.           Caution: java.util.Observable is not an interface, though
  2433.           java.util.Observer is. These two are poorly designed.
  2434.        3. Object and data (field) names are nouns/noun phrases, with the
  2435.           first letter lowercase, and the first letter of subsequent words
  2436.           capitalized: currentLimit
  2437.        4. Method names are verbs/verb phrases, with the first letter
  2438.           lowercase, and the first letter of subsequent words capitalized:
  2439.           calculateCurrentLimit
  2440.        5. Constant (final) names are in caps: UPPER_LIMIT
  2441.        6. Also in the FAQ:
  2442.           Where can I find a Java style guide on naming conventions?
  2443.           Other sites:
  2444.           JLS 6.8 Naming Conventions
  2445.  
  2446.   9. (Sect. 6) Should I prefer importing {package}.{class} over {package}.*?
  2447.  
  2448.      Does it make a difference to the class file in any way, if I import a
  2449.      package versus use the full name, i.e.
  2450.  
  2451.          import java.rmi.server.*;
  2452.          ...
  2453.          RemoteObject ro;
  2454.  
  2455.      versus:
  2456.  
  2457.          java.rmi.server.RemoteObject ro;
  2458.  
  2459.      [*] No, it makes no difference to the class files or runtime speed.
  2460.      Import is just a shorthand for quoting the full name package and class
  2461.      name (as in the examples in the question). Importing a class does not
  2462.      cause the class to be loaded at run time. There is no runtime penalty
  2463.      for using the * form of import. The class file will contain the name of
  2464.      the packages it uses, and the loader will look for those classes as
  2465.      needed at runtime.
  2466.  
  2467.      At compile time, the different forms of import may or may not make a
  2468.      difference to compile time. Such a difference is likely to be
  2469.      negligible, and should not be a factor in which form of import you use.
  2470.  
  2471.      However, there are style advantages. Some say that stating which
  2472.      classes you are importing can help program readability. In a program
  2473.      with many * import statements, it may take a programmer time to find
  2474.      which package an obscure class is imported from. If you explicitly list
  2475.      each class you import at the top of the program, you document which
  2476.      package each class you use comes from. These people suggest that you
  2477.      use
  2478.  
  2479.      import java.rmi.server.RemoteObject;
  2480.  
  2481.  
  2482.      in preference to:
  2483.  
  2484.      import java.rmi.server.*;
  2485.  
  2486.  
  2487.      Other people say that it is clearer still to use the full package and
  2488.      class name, at the point where you use classes in other packages.
  2489.      These people suggest that you use:
  2490.  
  2491.      java.rmi.server.RemoteObject ro;
  2492.  
  2493.  
  2494.      But that gets a little lengthy when you instantiate:
  2495.  
  2496.              java.rmi.server.RemoteObject ro
  2497.                        = new java.rmi.server.RemoteObject();
  2498.  
  2499.  
  2500.      You always have the option of stating the full package and class name,
  2501.      whether you use import or not.
  2502.  
  2503.      Another good reason not to use the * form is when you are importing two
  2504.      packages that have classes of the same name and you want to use only
  2505.      one of those classes. E.g.
  2506.  
  2507.          import com.sun.*;
  2508.          import com.ms.*;
  2509.  
  2510.  
  2511.      where there is a class called Modem in both those packages. If you use
  2512.      the * form of import, you import both of the Modem classes and then
  2513.      must fully qualify the class each time you use it, to say which of the
  2514.      two you mean. In Java 1.2, the class java.util.List was introduced.
  2515.      That had the same unqualified name as java.awt.List. If your code had
  2516.      "import java.awt.*; import java.util.*;" it would no longer compile.
  2517.      You'd get a message about ambiguous classname. If you import all of a
  2518.      package indiscriminately you might get bitten when the package API
  2519.      changes.
  2520.  
  2521.      In Java 1.0, if you import a class that has the same name as a class
  2522.      defined in that source file, you will get an error that the class names
  2523.      clash. In Java 1.1, the local class will be used when the package name
  2524.      is not given; to use the imported class, you have to use the full
  2525.      package name.
  2526.  
  2527.      The best advice is to write the program so that it is as readable as
  2528.      possible. Where you have a group of well-known classes, as in java.awt,
  2529.      there is no reason not to use "import java.awt.*;"
  2530.  
  2531.  10. (Sect. 6) How can I use Math.cos() etc. without the prefix "Math."?
  2532.      Is there some declaration that I can use to make "acos", "cos", "sin",
  2533.      etc. (from java.lang.Math) recognizable in my own class, so I don't
  2534.      have to prefix "Math." to them?
  2535.  
  2536.      [*] No. There is no good alternative. There are several bad
  2537.      alternatives:
  2538.        1. Using "import" doesn't work.
  2539.           The import stament only imports packages, subpackages, and
  2540.           classes, not class members. This doesn't work:
  2541.  
  2542.                   import java.lang.Math.*;
  2543.  
  2544.  
  2545.        2. Minimizing class name usage is unclear and bad style.
  2546.           - You could wrap the functions in your own class.
  2547.  
  2548.               double sin(double x) {
  2549.                   return Math.sin(x);
  2550.               } // etc. for each function
  2551.  
  2552.  
  2553.           But you'd have to use your class name everywhere but inside your
  2554.           class, so it doesn't help.
  2555.           - You can make a null reference to the Math class and use it to
  2556.           refer to the static methods. Declare
  2557.  
  2558.               java.lang.Math M = null;
  2559.               angle = M.cos(i);
  2560.  
  2561.  
  2562.           Besides not being clear, this invites abuse and errors.
  2563.  
  2564.           - You could inherit the names
  2565.           If java.lang.Math were not final and your class did not extend
  2566.           another class, you could have your class extend Math, to bring the
  2567.           namespace in. However, it is poor OOP style to use inheritance to
  2568.           obtain a name abbreviation rather than to express a type
  2569.           hierarchy.
  2570.  
  2571.  11. (Sect. 6) Why is there a standard JNI?
  2572.  
  2573.      [*] JNI is the Java Native Interface. It defines the way that a Java
  2574.      program can call C programs. The industry has agreed on, and Sun has
  2575.      codified, JNI as the standard. Microsoft shuns the standard and uses a
  2576.      protocol of its own called Raw Native Interface, RNI.
  2577.  
  2578.      You might think that once a Java program uses JNI, portability is lost,
  2579.      and hence it doesn't matter if vendors diverge from the JNI standard.
  2580.      Not so. Code that accesses a native library using JNI can run on any VM
  2581.      that supports JNI, so it's portable across VMs on the same platform.
  2582.      Further, you can port a native library to all platforms Java supports
  2583.      (indeed, this is how Sun implements the Java Platform), so JNI
  2584.      _enables_ cross-platform development where it's necessary to use
  2585.      platform-specific idioms for certain functionality.
  2586.  
  2587.      Conversely, code that uses RNI can only run on Microsoft's VMs on the
  2588.      win32 platform. Microsoft's RNI has the effect of limiting RNI programs
  2589.      to the Microsoft VM. Further, Microsoft's failure to support JNI locks
  2590.      out JNI-based functionality on Windows. Microsoft's non-standard RNI is
  2591.      the reason that programs using the Microsoft JVM cannot use the
  2592.      standard Java jdbc-odbc library. That library has a piece written in C.
  2593.      It works for all JVMs except Microsoft's.
  2594.  
  2595.      The standard JNI thus has two purposes:
  2596.        1. Source code compatibility between different platforms.
  2597.        2. Binary code compatibility between different JVMs on the same
  2598.           platform.
  2599.      Microsoft's use of RNI locks in programmers who use it, and Microsoft's
  2600.      failure to support JNI locks out programmers who don't use RNI. Users
  2601.      can't run standard JNI applications on Microsoft VMs, or RNI
  2602.      applications on non-Microsoft VM's. As a result, since most users will
  2603.      support only one VM, they'll be locked in to complementary software -
  2604.      in the case of Microsoft, a proprietary standard. A standard JNI means
  2605.      that you can use any standard JVM to run your code on this platform.
  2606.  
  2607.  12. (Sect. 6) How do I find out more about JNI? How do I find out more
  2608.      about Java Anything?
  2609.  
  2610.      [*] Taking the questions one at a time. Use of JNI detracts from
  2611.      program portability. So you would only do it when you need some
  2612.      critical single-platform effect. The documentation on JNI is at:
  2613.      http://java.sun.com/docs/books/tutorial/native1.1/index.html
  2614.  
  2615.      If your interest extends to reading a book on JNI, a good one is
  2616.      "Essential JNI Java Native Interface" by Rob Gordon; ISBN
  2617.      0-13-679895-0. See
  2618.      http://www.amazon.com/exec/obidos/ASIN/0136798950/afuinc
  2619.  
  2620.      In general, if you want to find out about topic "X" in Java, your first
  2621.      stop should be to search the http://java.sun.com website for "X". For
  2622.      example if you want to know about Internationalization in Java, a
  2623.      search at the site quickly takes you to
  2624.      http://java.sun.com/products/jdk/1.1/docs/guide/intl/intlTOC.doc.html.
  2625.  
  2626.  13. (Sect. 6) How do I get unsigned ints in Java?
  2627.  
  2628.      [*] Java doesn't have unsigned ints. The reason is that this is a
  2629.      poorly designed area of C. The rules for what type you end up with when
  2630.      you mix signed and unsigned in expressions are complicated, and they
  2631.      changed between K&R and ANSI C (you might have heard this under the
  2632.      name "unsigned preserving vs. value preserving"). Worse, they depended
  2633.      on the underlying hardware, so they varied from platform to platform,
  2634.      causing bugs in all kinds of unexpected places. The book "Expert C
  2635.      Programming" goes into this in more depth (page 25). So, to avoid
  2636.      bringing over the hidden complexities, Java does not bring over
  2637.      unsigned types from C.
  2638.  
  2639.      Use type char if you are OK with 16-bit unsigned quantities. Otherwise,
  2640.      go to the next larger type and use masking. If you don't have to worry
  2641.      about division by numbers with the high bit set, then when you use >>>
  2642.      for right shift and remember to AND each byte with 0xFF where they are
  2643.      being expanded into a larger type, then there is no difference in the
  2644.      bit patterns generated.
  2645.  
  2646.      Specifically, to convert an int to its unsigned representation, use:
  2647.  
  2648.              ((long)i) & 0x00000000FFFFFFFFL
  2649.  
  2650.  
  2651.      This promotes the signed (and possibly negative) int to long (with sign
  2652.      extension) then chops off the sign-extension, leaving it as the same
  2653.      32-bit quantity held in a 64-bit type.
  2654.      Also worth noting is that if you're going to work with unsigned bytes,
  2655.      int is a more efficient larger type to use than short or char, since
  2656.      smaller values have to be promoted to int to do any arithmetic or
  2657.      testing on them.
  2658.  
  2659.  14. (Sect. 6) What happened to "private protected"?
  2660.  
  2661.      [*] It first appeared in JDK 1.0 FCS (it had not been in the betas).
  2662.      Then it was removed in JDK 1.0.1. It was an ugly hack syntax-wise, and
  2663.      it didn't fit consistently with the other access modifiers. It never
  2664.      worked properly: in the versions of the JDK before it was removed,
  2665.      calls to private protected methods were not dynamically bound, as they
  2666.      should have been. It added very little capability to the language. It's
  2667.      always a bad idea to reuse existing keywords with a different meaning.
  2668.      Using two of them together only compounds the sin.
  2669.  
  2670.      The official story is that it was a bug. That's not the full story.
  2671.      Private protected was put in because it was championed by a strong
  2672.      advocate. It was pulled out when he was overruled by popular
  2673.      acclamation.
  2674.  
  2675.      Inheritance
  2676.  
  2677.  15. What are the differences between an interface and an abstract class?
  2678.  
  2679.      [*] Some use a semantic distinction: an abstract superclass models the
  2680.      "is" relationship, while an interface models the "has" relationship.
  2681.      The rule would be, if it's a subtype, inherit; otherwise, implement.
  2682.  
  2683.      But, in the absence of real-world characteristics to distinguish the
  2684.      objects from their properties and parents, that becomes a circular
  2685.      argument. In this case, you have to look at the practical differences
  2686.      in Java (compared with C++).
  2687.  
  2688.      Most differences between interfaces and abstract classes stem from
  2689.      three characteristics:
  2690.        1. Both define method signatures that a derived class will have.
  2691.        2. An abstract class can also define a partial implementation.
  2692.        3. A class can implement many interfaces, but inherit from only one
  2693.           class.
  2694.  
  2695.      In greater detail, these topics are:
  2696.        1. Method signatures Both interfaces and abstract classes permit one
  2697.           to treat the derived-type class as the derived-from-type class.
  2698.           Both define a set of available methods in a way that can be
  2699.           enforced by the type-checking mechanism. This is typically used to
  2700.           permit different (derived) types to behave in the same way (as
  2701.           what they are derived from - i.e., they all support particular
  2702.           methods). For example, all java.* types can be printed as Strings
  2703.           because Object, the superclass of all java.* types, has a
  2704.           toString() method. Similarly, all types that implement the
  2705.           Observable interface can be passed an Observer to signal when an
  2706.           event has occurred. This permits an algorithm or service to
  2707.           operate on different (derived) types as if they were the same
  2708.           (derived-from) type.
  2709.           This mechanism supports not only polymorphism (one object treated
  2710.           as another), but differentiation. In either case, the (derived)
  2711.           types can implement the method in the way appropriate to that
  2712.           type. However, you're not likely to override inherited
  2713.           functionality, but you must implement interface methods, so if you
  2714.           expect significant differentiation, then an interface might be
  2715.           warranted.
  2716.           Finally, this mechanism supports a weak variant of access control.
  2717.           Only inherited methods are available to callers who only have a
  2718.           reference to the superclass or interface type. It's weak because
  2719.           they can attempt a narrowing cast if they know their target type.
  2720.           Nonetheless, it reduces some complexity.
  2721.        2. Inheriting implementation Inheriting an implementation is useful
  2722.           where the code should be shared. This happens where derived types
  2723.           vary the functionality only a little bit, or where a complex set
  2724.           of method interfaces can through mutual reference be implemented
  2725.           with relatively few methods that can be implemented by derived
  2726.           types. You can also reuse code by having your class use or keep an
  2727.           object of another type that implements that code, but that doesn't
  2728.           permit your callers to treat you in a particular way. To both
  2729.           "get" functionality and to be treated "as" the superclass are the
  2730.           essentials of the type/subtype relationship.
  2731.        3. Java's rule of single inheritance Java differs from C++ in
  2732.           permitting only single inheritance. This makes for some difficult
  2733.           choices, if you would like to share combinations of inherited
  2734.           functionality and polymorphism from more than one source. However,
  2735.           it does reinforce the notion of inheritance as a subtyping (is)
  2736.           relationship, and implicitly that type relationships form a tree
  2737.           rather than a network.
  2738.  
  2739.      Other differences to consider:
  2740.        1. Abstract class implementations may include fields
  2741.        2. Interfaces may include final data members
  2742.        3. It is slightly slower to call an implemented method via an
  2743.           interface reference. There is an even smaller penalty for calling
  2744.           a superclass method via a subclass reference (i.e., where the
  2745.           subclass does not override the method). There is almost no penalty
  2746.           for calling a subclass method via a superclass reference. (All are
  2747.           compared to a direct method call, i.e., calling the derived class
  2748.           method via a derived class reference).
  2749.  
  2750.  16. (Sect. 6) How do static methods interact with inheritance?
  2751.  
  2752.      [*] Static (per-class, rather than per-object) methods do not
  2753.      participate in overriding (choosing the right method at runtime based
  2754.      on the class of the object). Probably the best and simplest way to
  2755.      think about this (and to write your code) is to write every invocation
  2756.      of a static method using the fully qualified class name:
  2757.  
  2758.          class A {
  2759.          public static method1() {
  2760.                  A.method2();
  2761.              }
  2762.          public static method2() {
  2763.              }
  2764.          }
  2765.  
  2766.          class B extends A {
  2767.              public static method3() {
  2768.                  A.method1();
  2769.              }
  2770.              public static method2() {
  2771.              }
  2772.          }
  2773.  
  2774.  
  2775.      Now it is perfectly clear that the static method2() that is called is
  2776.      A.method2(), not B.method2(). A.method2() will be called regardless of
  2777.      whether you use the fully-qualified class name or not, but using "A."
  2778.      makes it obvious to all.
  2779.  
  2780.  17. (Sect. 6) Why is the String class final? I often want to override it.
  2781.  
  2782.      [*] Being final guarantees that instances of String are read-only. (The
  2783.      String class implements read-only objects, but if it were not final it
  2784.      would be possible to write a subclass of String which permitted
  2785.      instances to be changed.) Strings need to be read-only for security and
  2786.      efficiency.
  2787.  
  2788.      As for efficiency, Strings are very commonly used, even behind the
  2789.      scenes by the Java compiler. Efficiency gains in the String class yield
  2790.      big dividends. If no one can change a String, then you never have to
  2791.      worry about who else has a reference to your String. It's easier to
  2792.      optimize accesses to an object that is known to be unchanging.
  2793.  
  2794.      Security is a more compelling reason. Before String was changed to be
  2795.      final (while Java 1.0 was still in beta) there was a race condition
  2796.      which could be used to subvert security restrictions. It had to do with
  2797.      one thread changing a pathname to a file after another thread had
  2798.      checked that the access was permitted and was about to open it.
  2799.  
  2800.      There are other ways to solve these problems, but the designers
  2801.      preferred making String final, particularly since the StringBuffer
  2802.      class is available as an alternative.
  2803.  
  2804.  18. (Sect. 6) If I extend/subclass a class, are the constructors inherited?
  2805.  
  2806.      [*] "Constructor declarations are not members. They are never inherited
  2807.      and therefore are not subject to hiding or overriding." The default
  2808.      constructor is not inherited, but provided. (See JLS 8.6.7 Default
  2809.      Constructors)
  2810.  
  2811.      If you don't give your child class any constructors, a default no-arg
  2812.      constructor that invokes the superclass' constructor is provided for
  2813.      you. If the superclass doesn't have a no-arg constructor, you should
  2814.      create a constructor and call the appropriate superclass constructor.
  2815.  
  2816.      Also in the FAQ:
  2817.      Compiler message No constructor {superclass}()
  2818.  
  2819.      Other sites:
  2820.      JLS 8.6.7 Default Constructors
  2821.  
  2822.  19. (Sect. 6) How can I safely store particular types in general
  2823.      containers?
  2824.      I often want to store particular types of objects but don't want to
  2825.      subclass my basic storage classes to enforce the particular type; that
  2826.      would make for too many subclasses (e.g., IntegerLinkedList,
  2827.      StringLinkedList, etc.).
  2828.  
  2829.      [*] Generic programming in java (the rough equivalent of C++'s
  2830.      templates) works reasonably well since all java classes are subclasses
  2831.      of Object. There is, however one potential problem - there is always a
  2832.      possibility that a generic container may contain different classes of
  2833.      objects.
  2834.  
  2835.      This naturally leads to the question of how to do this in a type-safe
  2836.      way. If you've created a generic LinkedList class, how can you be type
  2837.      safe without having to create a multitude of subclasses
  2838.      (IntegerLinkedList, StringLinkedList, etc.)?
  2839.  
  2840.      One way to handle this would be to offer up an additional constructor
  2841.      in your generic class that takes a parameter of type "Class" and uses
  2842.      that parameter along with Class's "isInstance" method to guarantee that
  2843.      Objects added to the container are the expected type.
  2844.  
  2845.          public class LinkedList {
  2846.              Protected Class type = Object.class;
  2847.  
  2848.              public LinkedList(Class type) { this.type = type; }
  2849.  
  2850.              public void addElement(Object element) throws Exception
  2851.              {
  2852.              if(!type.isInstance( element ))
  2853.                  throw new Exception(
  2854.                       "Expected element of type (" + type    + ")" +
  2855.                       " got element of type ("     + element + ")"   );
  2856.               ...
  2857.               }
  2858.           }
  2859.  
  2860.  
  2861.      Note that the comments in the source for isInstance() refer to a
  2862.      "specified Class parameter", suggesting that you are supposed to write
  2863.      something like:
  2864.  
  2865.              public void addElement(Object element) throws Exception
  2866.          {
  2867.              Class c = element.getClass();
  2868.              if(!type.isInstance(c))
  2869.  
  2870.  
  2871.      This works, but the documentation for isInstance is clear that the
  2872.      parameter should be an Object rather than a Class. Also, note that
  2873.      "Collections" are coming in JDK 1.2, and they provide a much safer and
  2874.      more extensible mechanism. More information about this is available at
  2875.      the Java Developer Connection at the Java website: http://java.sun.com/
  2876.  
  2877.      Method interfaces
  2878.  
  2879.  20. How do I send a variable number of arguments to a method?
  2880.  
  2881.      [*]
  2882.        1. (Easy) Use method overloading to support different parameters.
  2883.           This makes things easy on the caller but can get out of hand if
  2884.           you want to support a wide number and variety of parameter types.
  2885.           You should ask yourself if your code design is well-organized if
  2886.           you need to do this.
  2887.        2. (More complicated) Use arrays. It's even possible to declare
  2888.           arrays inline as shown below:
  2889.  
  2890.               foo("A param",
  2891.                   new Object[] {"param3", "param4", new Integer(5)} );
  2892.            // ...
  2893.  
  2894.            void foo(String param1, Object param2[]) {
  2895.                System.out.println(param1);
  2896.                for (int i = 0; i < param2.length; i++) {
  2897.                    System.out.println(param2[i].toString());
  2898.                }
  2899.            }
  2900.  
  2901.  
  2902.           You can even pass arrays of arrays using this method. Of course,
  2903.           inside the method you need to be able to decode what the arguments
  2904.           are and how you use them.
  2905.        3. Alternatively you can invent a class that just contains all the
  2906.           possible fields you might want to pass into a method (plus
  2907.           booleans to say if each field is set or not), and make an object
  2908.           of that class be a parameter to the method. You can return
  2909.           multiple values from a method the same ways; either have the
  2910.           method return an array or a wrapper object.
  2911.  
  2912.      However, remember the wise words of Professor Alan Perlis, "if your
  2913.      procedure has more than about half a dozen parameters, you probably
  2914.      forgot a few." Passing large numbers of arguments into a function
  2915.      suggests your function is badly organized.
  2916.  
  2917.  21. (Sect. 6) How can I return a different object in a method parameter?
  2918.      How can I pass an object to a method, and have the method change the
  2919.      reference so it points to a different object back in the calling code?
  2920.  
  2921.      indirection". Wrap the object in another class, whose purpose is simply
  2922.      to be passed as a parameter, allowing the nested object reference to be
  2923.      modified.
  2924.      The second alternative is a clearer variant of this. Pass in a single
  2925.      element array. Since arrays are objects, this works.
  2926.  
  2927.              void jfoo(Object ref[]){
  2928.              ref[0] = new Object();
  2929.          }
  2930.          ...
  2931.          Object kludge[] = new Object[1];
  2932.          kludge[0]= myObj;
  2933.          jfoo(kludge);
  2934.          if (kludge[0] == myObj) ...
  2935.          else ...
  2936.  
  2937.  
  2938.      Note that changing a global variable/object inside a method is an
  2939.      egregious programming practice; it usually violates basic OOP
  2940.      constructs.
  2941.  
  2942.  22. (Sect. 6) How do I get multiple return values back from a method?
  2943.  
  2944.      [*] You can just have the function return a Vector. This is
  2945.      particularly convenient when you're not sure how much you are going to
  2946.      be returning, based on what occurs in the method. A Vector is
  2947.      essentially a dynamically-growable array. Regular arrays can't grow
  2948.      after you declare them - you have to declare a bigger array and move
  2949.      the old stuff into it.
  2950.  
  2951.      Arrays
  2952.  
  2953.  23. (Sect. 6) How do I allocate a multidimensional array?
  2954.  
  2955.      [*] There are several ways. If you want a rectangular array, you can
  2956.      allocate the space for the array all at once. The following creates a
  2957.      4x5 array:
  2958.  
  2959.          int arr[][] = new int[4][5];
  2960.  
  2961.  
  2962.      If you want each row to have a different number of columns, you can use
  2963.      the fact that a two-dimensional array is actually an array of arrays.
  2964.      The following code allocates a triangular array:
  2965.  
  2966.          int arr[][] = new int[4][];    // allocate the four row arrays
  2967.          for (int i = 0; i < 4; i++) // initialize each of the four rows
  2968.          arr[i] = new int[i + 1];       // row i has i + 1 columns
  2969.  
  2970.  
  2971.      Note that if you allocate an array of any kind of object (as opposed to
  2972.      primitive type), all the references will be null by default. These null
  2973.      references can result in NullPointerExceptions if you try to
  2974.      dereference them.
  2975.      In other words, after doing:
  2976.  
  2977.          int arr[] = new int[4];
  2978.  
  2979.  
  2980.      you can say
  2981.  
  2982.              if (arr[2] == 0)
  2983.  
  2984.  
  2985.      But after doing
  2986.  
  2987.              Integer Iarr[] = new Integer[4];
  2988.  
  2989.  
  2990.      you must fill in the object reference before using it. E.g.,
  2991.  
  2992.              Iarr[2] = myInt;
  2993.  
  2994.  
  2995.      or
  2996.  
  2997.              arr[2] = new Int(27);
  2998.  
  2999.  
  3000.      before you can say
  3001.  
  3002.              if (Iarr[2].equals(myInt))
  3003.  
  3004.  
  3005.  24. (Sect. 6) How do I copy an array?
  3006.  
  3007.      [*] If the array only contains primitive types or if you want to copy
  3008.      only the object references, not duplicate the objects, then use the
  3009.      method
  3010.  
  3011.          java.lang.System.arraycopy(Object src, int src_position,
  3012.              Object dst, int dst_position, int length);
  3013.  
  3014.  
  3015.      Otherwise, if you want to duplicate the objects, you have to initialize
  3016.      your new array and write a loop that duplicates each object in the old
  3017.      array into the new.
  3018.  
  3019.      Note that the documentation for arraycopy() says that if src and dst
  3020.      refer to the same object, then arraycopy behaves as if the source array
  3021.      elements are copied into a temporary array (i.e., they are preserved).
  3022.      Some interpret this as meaning a temporary array will be so allocated,
  3023.      but that's not Sun's implementation.
  3024.  
  3025.      Other sites:
  3026.      JLS 20.18.16 {java.lang.System.arraycopy()}
  3027.  
  3028.  25. (Sect. 6) How do I clear an array?
  3029.  
  3030.      [*] There is no method to clear an array to 0.0, 0, null, false,
  3031.      '\u0000' etc. When you allocate an array, the elements are set to their
  3032.      default values, but that doesn't help when you want to reuse an array.
  3033.  
  3034.      If you want to set the same array to the same set of values many times,
  3035.      create a template array. Fill it with the reset value, then use
  3036.      System.arraycopy() to copy it into the work array each time you need to
  3037.      set the work array.
  3038.  
  3039.  26. (Sect. 6) What is a fast way to set all elements of an array?
  3040.      I don't want to use a template array. I would like to set all array
  3041.      elements to a given value without duplicating the (possibly large)
  3042.      array.
  3043.  
  3044.      [*] Using a loop that does it one by one is probably 20 to 40 times
  3045.      slower than good old memset() in C.
  3046.  
  3047.      A fast way on many VM's is to set the first byte of the array, then use
  3048.      System.arraycopy() repeatedly to fill the next byte, the next two
  3049.      bytes, the next four bytes, the next eight bytes, etc., and when you
  3050.      get past halfway, fill in the rest.
  3051.  
  3052.          public static void bytefill(byte[] array, byte value) {
  3053.          int len = array.length;
  3054.          if (len > 0)
  3055.          array[0] = value;
  3056.          for (int i = 1; i < len; i += i)
  3057.              System.arraycopy( array, 0, array, i,
  3058.                  ((len - i) < i) ? (len - i) : i);
  3059.          }
  3060.  
  3061.  
  3062.      This is faster on Sun's VM than a simple loop, and probably even faster
  3063.      under JITs because it only performs at most log2(array.length) bounds
  3064.      checks. This is a clever code idiom applying the binary chop algorithm
  3065.      to arrays even when their size is not a power of 2.
  3066.  
  3067.                        -------------------------------
  3068.  
  3069. 7. I/O
  3070.  
  3071.   1. (Sect. 7) How do I read a file containing ASCII numbers?
  3072.  
  3073.      [*] There are several ways to do this. Here is one way. Let's assume
  3074.      your file is called "C:\work\mydata.txt" and it contains lines like:
  3075.  
  3076.          135   7512   3659814  328   1 54829
  3077.          68522 19982810  38
  3078.  
  3079.      i.e. lines contain several ASCII strings that are numbers separated by
  3080.      spaces.
  3081.      The code fragment is as follows:
  3082.  
  3083.      //  Open the file with
  3084.      RandomAccessFile f = new RandomAccessFile("c:\\work\\datafile.txt", "r");
  3085.  
  3086.      // read an entire line from it
  3087.      String s= f.readLine();
  3088.  
  3089.      // get some methods to break up a line into tokens
  3090.      StringTokenizer st = new StringTokenizer(s);
  3091.  
  3092.      // extract the next int from the line
  3093.      i = Integer.parseInt(st.nextToken());
  3094.  
  3095.      We use a RandomAccessFile because that supports the readLine() method
  3096.      directly. An alternative would be to instantiate a FileReader, and wrap
  3097.      a BufferedReader around it. Putting it all together, including the
  3098.      exception handling in the event the file is missing, the code looks
  3099.      like:
  3100.  
  3101.      import java.io.*;
  3102.      import java.util.*;
  3103.      public class c  {
  3104.          public static void main(String args[]) {
  3105.            try {
  3106.              RandomAccessFile f = new RandomAccessFile
  3107.                                              ("datafile.txt", "r");
  3108.              String s;
  3109.              while ( (s=f.readLine()) != null )  {
  3110.                  System.out.println("read: "+s);
  3111.  
  3112.                  StringTokenizer st = new StringTokenizer(s);
  3113.                  int i=0;
  3114.                  while (st.hasMoreTokens()) {
  3115.                     i = Integer.parseInt(st.nextToken());
  3116.                     // i now holds the next int on the line
  3117.                     // could also use Double.parseDouble(), etc.
  3118.  
  3119.                     System.out.print(" "+ i);
  3120.                  }
  3121.                  System.out.println();
  3122.              }
  3123.  
  3124.            } catch (Exception e) {System.out.println("Excpn: "+e); }
  3125.            // file I/O, from book "Just Java" by Peter van der Linden
  3126.          }
  3127.      }
  3128.  
  3129.      See also the next question on how to read data interactively.
  3130.  
  3131.   2. (Sect. 7) How do I read a String/int/boolean/etc from the keyboard?
  3132.  
  3133.      [*] The easiest way is to pick up the source for the 100% pure Java
  3134.      class EasyIn from http://www.afu.com/ (same place as this FAQ). Compile
  3135.      it with your code and use it like this:
  3136.  
  3137.      EasyIn easy = new EasyIn();
  3138.  
  3139.      int i = easy.readInt(); // gets an int from System.in
  3140.      boolean b = easy.readBoolean(); // gets a boolean from System.in
  3141.      double d = easy.readDouble(); // gets a double from System.in
  3142.  
  3143.  
  3144.      ... etc.
  3145.  
  3146.      EasyIn is free, comes with source, and you can do what you like with
  3147.      it, including improve it, and send me back the results.
  3148.  
  3149.      If, instead, you want to "roll your own" code (why?!), in JDK 1.0.2
  3150.  
  3151.      java.io.DataInputStream in = new java.io.DataInputStream(System.in);
  3152.      String s = in.readLine();
  3153.  
  3154.  
  3155.      One way in JDK 1.1:
  3156.  
  3157.      java.io.BufferedReader in =
  3158.       new java.io.BufferedReader( new InputStreamReader(System.in));
  3159.  
  3160.      String s = in.readLine();
  3161.  
  3162.  
  3163.      Once you have the token in a String, it is easy to parse it into one of
  3164.      the other types, as shown earlier in the FAQ. Yes, it is bone-headed,
  3165.      as it makes the simplest case of keyboard I/O unnecessarily
  3166.      complicated. A bug was filed with Javasoft to record this problem, but
  3167.      don't count on this being fixed any time soon.
  3168.  
  3169.   3. (Sect. 7) Why do I have trouble with System.out.println()?
  3170.  
  3171.      [*] Check the spelling. The last two characters are the letters "ell
  3172.      enn" not "one enn".
  3173.  
  3174.      The name of the method stands for "print line", since it prints a
  3175.      String and goes to the next line, rather than staying on the same line
  3176.      as System.out.print() does. Yes, the name is yet another Java naming
  3177.      inconsistency, since the input equivalent is readLine(), not readln().
  3178.  
  3179.   4. (Sect. 7) How do I write to the serial port on my PC using Java?
  3180.  
  3181.      [*] There is a platform-independent serial port API introduced in JDK
  3182.      1.2. You can download the documentation by registering with the Java
  3183.      Developer Connection (it's free, http://java.sun.com) and browsing
  3184.      http://java.sun.com/jdc/earlyAccess/communications.html.
  3185.  
  3186.      For systems prior to JDK 1.2, read on. At least two companies have
  3187.      written a library to drive the port. See
  3188.         o http://www.sc-systems.com has a library for Windows 95, WindowsNT,
  3189.           OS/2, Macintosh PPC, Solaris Sparc, Linux x86, FreeBSD x86, HP/UX
  3190.           PA-RISC, and possibly others too.
  3191.         o http://www.cd.com/portio
  3192.         o In addition, there is a Unix serial port utility available with
  3193.           source at http://jarvi.ezlink.com/rxtx/ It's free under the GPL,
  3194.           and works on Linux, Irix, Solaris, Windows 95, and NT.
  3195.  
  3196.      While not helpful to typical home users, there is an alternative
  3197.      portable COM port solution for Java 1.1 and even 1.0. Buy your COM
  3198.      ports in the form of "terminal servers". Using a COM port is now as
  3199.      easy as connecting to it with a Socket. Port parameters can be changed
  3200.      programatically using SNMP for most terminal servers (but this is never
  3201.      necessary when a modern modem or other fixed-rate equipment is
  3202.      attached). Any networked box can serve as a terminal server - even
  3203.      Win95 - with a simple native server application for that box, but
  3204.      buying an actual firmware based hardware box is much easier.
  3205.  
  3206.      Furthermore, your Win95 native applications can now share the COM ports
  3207.      (and any attached modems) via a Win95 product called "Dial-out IP" at
  3208.      http://www.tactical-sw.com/.
  3209.  
  3210.      If the port exists as a pathname in the filesystem, you can open it as
  3211.      a file and read/write. You can also print text this way by writing to
  3212.      "prn" or "lpt1" on a pc, and "/dev/something" on Unix. Writing a
  3213.      formfeed at the end of the file is essential on Windows 95. Here is
  3214.      some sample code:
  3215.  
  3216.      // class that opens the printer as a file
  3217.      // and writes "Hello World" to it
  3218.  
  3219.      import java.io.*;
  3220.      public class lpt {
  3221.          public static void main (String[] argv) {
  3222.              try {
  3223.                  FileOutputStream os = new FileOutputStream("LPT1");
  3224.                  //wrap stream in "friendly" PrintStream
  3225.                  PrintStream ps = new PrintStream(os);
  3226.  
  3227.                  //print text here
  3228.                  ps.println("Hello world!");
  3229.  
  3230.                  //form feed -- this is important
  3231.                  //Without the form feed, the text will simply sit
  3232.                  // in print buffer until something else gets printed.
  3233.                  ps.print("\f");
  3234.                  //flush buffer and close
  3235.                  ps.close();
  3236.              } catch (Exception e) {
  3237.                  System.out.println("Exception occurred: " + e);
  3238.              }
  3239.          }
  3240.      }
  3241.  
  3242.  
  3243.      If you wish to change the characteristics of the port (e.g. baud rate,
  3244.      parity, etc.), not just read/write data, Java currently offers no
  3245.      portable way to do this. You will need to use one of the packages
  3246.      mentioned above or some native code or a system command.
  3247.  
  3248.   5. (Sect. 7) How do I append to a file?
  3249.  
  3250.      [*] There are two ways. JDK 1.1 introduced new constructors for two of
  3251.      the output classes that allowed you to set a boolean flag:
  3252.  
  3253.      public FileWriter(String fileName, boolean append) throws IOException
  3254.      public FileOutputStream(String name, boolean append) throws IOException
  3255.  
  3256.  
  3257.      Another way is to do this:
  3258.  
  3259.      RandomAccessFile fd = new RandomAccessFile(file,"rw");
  3260.      fd.seek(fd.length());
  3261.  
  3262.  
  3263.      Then write using fd. Note that the latter method does not take
  3264.      advantage of the "append" mode present in many operating systems (such
  3265.      as all Unixes). Such a difference may make a difference with multiple
  3266.      processes or threads appending to the same output file. This can happen
  3267.      frequently, even if not intended by the programmer, e.g. with logfiles
  3268.      in multitasking environments.
  3269.  
  3270.   6. (Sect. 7) Is it possible to lock a file using Java ?
  3271.  
  3272.      [*] JDK 1.2 introduces the ability to lock a file (indirectly) using
  3273.      the File class. Use createTempFile() with delete on exit. Prior
  3274.      releases of Java do not feature an API to lock a file or regions within
  3275.      a file. Code that needs to do this must take one of four approaches:
  3276.        1. Implement an advisory locking scheme using features that Java does
  3277.           have (synchronized methods). This allows you to lock files against
  3278.           use by other Java code running in the same JVM.
  3279.  
  3280.        2. Use the atomic operation File.createNewFile(), and mark it as
  3281.           deleteOnExit(). Have all processes (Java and non-Java) follow the
  3282.           same protocol: if the create operation succeeded, you have the
  3283.           lock. To give up the lock, you either delete the file or exit the
  3284.           JVM.
  3285.  
  3286.           Note that this may fail if the file is remotely mounted using NFS
  3287.           version 2. (There's a window of opportunity bewteen the LOOKUP to
  3288.           see if it's already there, and the CREATE if it's not). However,
  3289.           NFS version 3 does guarantee exclusive create of remotely mounted
  3290.           files, and is not subject to this race condition failure.
  3291.  
  3292.        3. Make calls to native code to issue the locking ioctls. This
  3293.           approach is not portable, but gives you a shot at having your
  3294.           locks respected by legacy code in non-Java programs using standard
  3295.           locking ioctls.
  3296.  
  3297.        4. Push the work to a central server. Since socket connection
  3298.           requests arrive in a single queue on the server, this can be used
  3299.           to serialize lock requests. There might be some merit in copying
  3300.           the NFS lockd protocol for a general approach. Rolling your own
  3301.           simple version for a specific application is pretty easy. A
  3302.           database would be better off locking records or fields, not byte
  3303.           offsets. In theory, the server socket approach would make it
  3304.           easier to perform automatic cleanup of a lock on abrupt VM process
  3305.           failure, e.g. by asking "are you still alive?" to the lock holder
  3306.           occasionally.
  3307.  
  3308.   7. (Sect. 7) How do I make the keyboard beep in Java?
  3309.  
  3310.      [*] In JDK 1.1, java.awt.Toolkit has the method beep(). The pre-1.1
  3311.      alternative of
  3312.  
  3313.      System.out.print("\07");
  3314.      System.out.flush();
  3315.  
  3316.      (the ASCII BEL character) doesn't work on Macs, but does on some other
  3317.      platforms. Java doesn't support the C abstraction of '\a' for an alert
  3318.      character.
  3319.  
  3320.   8. (Sect. 7) How do you do file I/O from an applet?
  3321.  
  3322.      [*] For security reasons, untrusted applets accessed across the network
  3323.      are restricted from doing certain operations, including I/O. This
  3324.      prevents rogue applets from sending out your private data, or deleting
  3325.      it. A trusted (signed) applet can perform these operations (JDK 1.1
  3326.      on).
  3327.  
  3328.      The simplest approach for server-side I/O is to use the Linlyn class
  3329.      available from http://www.afu.com. This is free software under the GNU
  3330.      license, and uses FTP to move files between an applet and the server.
  3331.      It is suitable for low-volume non-critical use like keeping a
  3332.      high-score file. The Linlyn class has a very simple application
  3333.      programmer interface.
  3334.  
  3335.         o The following suggestion is for server-side input.
  3336.  
  3337.           You can read a file on the server if you can create a URL
  3338.           referencing the file. Then open a stream, then use any of the
  3339.           stream-based methods to read.
  3340.  
  3341.           This allows reading but not writing. It requires an http daemon
  3342.           running on the server, which will usually be the case.
  3343.  
  3344.           try{
  3345.              URL url = new URL("http://somewhere.com/test.txt");
  3346.            // or URL url = new URL( getDocumentBase(), filename);
  3347.              BufferedReader in = new BufferedReader(
  3348.                                    new InputStreamReader(
  3349.                                       url.openStream() ) );
  3350.              String s = in.readLine(); //read till you get a null line.
  3351.              } catch(MalformedURLException e){
  3352.                      System.out.println("URLException:"+e);
  3353.              } catch(IOException e){
  3354.                      System.out.println("IOException:"+e);
  3355.              }
  3356.           }
  3357.  
  3358.  
  3359.           You cannot write a file on the server this way.
  3360.         o The following suggestions are for server-side output.
  3361.  
  3362.           It absolutely requires the cooperation of the server to allow an
  3363.           applet to write a file to the server. This cooperation may take
  3364.           any of several forms:
  3365.              + FTP server
  3366.              + File server (webnfs or custom written)
  3367.              + Listening on a socket for data from applets
  3368.              + CGI script
  3369.              + Java RMI (remote method invocation)
  3370.              + JDBC process
  3371.  
  3372.           In particular:
  3373.              + FTP code. Use the Linlyn class mentioned above.
  3374.              + WebNFS. This is an evolution of the NFS (Network File System)
  3375.                to make file resources visible in browsers. More information
  3376.                at http://www.sun.com/webnfs
  3377.              + Open a socket back to the server and read/write the data.
  3378.                Have a process on the server that listens for socket
  3379.                connections from applets and does the requisite I/O. This
  3380.                does I/O on the server.
  3381.              + Or use a CGI script or servlet on the server to write when
  3382.                browsed.
  3383.  
  3384.         o The following suggestions are for client-side I/O. Use a trusted
  3385.           applet (see section on security). This will permit local I/O
  3386.           without any of the restraints mentioned above. In this regard, the
  3387.           appletviewer and many other browsers regard applets loaded from a
  3388.           local filesystem (rather than across the net) as being more
  3389.           trustworthy, and perhaps even allowed to do I/O.
  3390.         o The simplest form of output is probably for the applet to connect
  3391.           to the mailserver port on the server, and prompt the user to enter
  3392.           his email address. Then email him the data to save locally if he
  3393.           wishes. If a small amount of data he can later enter it by
  3394.           cut-and-paste into the applet when he next invokes it.
  3395.         o Or use a browser that has a security policy that is configured to
  3396.           allow file I/O (such as Sun's appletviewer).
  3397.         o Read this article
  3398.           http://www.javareport.com/html/features/archive/9802/somers.shtml
  3399.           for an introduction to the basics.
  3400.  
  3401.   9. (Sect. 7) What are Resources files and how do they work?
  3402.  
  3403.      [*] In Java 1.1 and above, a resource file is a file that your code
  3404.      should be able to access no matter where it was loaded from: the local
  3405.      file system, via http, or some other means. This is a different concept
  3406.      than system resources. See question (TBD) for more information about
  3407.      system resources. (Volunteer sought to write answer on system resource
  3408.      files).
  3409.  
  3410.      There are two ways to specify resources.
  3411.         o using an absolute path name, such as
  3412.           "/myPackage/resourcedir/myResource.txt"
  3413.           With an absolute path name, the resource file is actually relative
  3414.           to the classpath.
  3415.         o using a relative path such as "dir/myResource.txt".
  3416.           If you specify a relative path, then the file is found relative to
  3417.           where the class loader found the package of the Class that is
  3418.           loading the resource. The consequence of this is that relative
  3419.           resource files can only be in the same directory as your class
  3420.           file or in a directory below.
  3421.      If you want to access resources from an unsigned applet, use relative
  3422.      resources.
  3423.  
  3424.      There are a couple of methods to get at resources, including methods in
  3425.      the java.lang.Class and java.lang.Classloader. It uses the class loader
  3426.      because that code knew where to find the class on the filesystem. If
  3427.      the resource file is nearby, it can be found the same way. One simple
  3428.      method to get a stream for a resource for a particular class, say
  3429.      Mypackage.MyClass, is as follows:
  3430.  
  3431.      String relativePath = "resourceDir/somefile.txt";
  3432.      String absolutePath = "/somePackage/somefile.txt";
  3433.      InputStream in=Mypackage.MyClass.class.getResourceAsStream(relativePath);
  3434.  
  3435.      If the class cannot be loaded, "in" would be assigned a null value.
  3436.      Otherwise, you can use the inputStream just as any other.
  3437.  
  3438.      A brief note about the syntax used above. In java 1.1 and above, a
  3439.      java.lang.Class object for a particular class can be acquired by
  3440.      appending .class to the class's name. Though it looks like every object
  3441.      has a static member variable, this is not actually the case.
  3442.  
  3443.      When using resources with Netscape, be aware of the Netscape
  3444.      restrictions that:
  3445.         o Netscape does not implement the getResource() methods in
  3446.           java.lang.Class and java.lang.ClassLoader, but only
  3447.           getResourceAsStream() methods.
  3448.         o All resources must be in a Jar/archive file
  3449.         o Resource files must have a Netscape-approved extension, or you
  3450.           must call certain functions before hand. See the following for
  3451.           details:
  3452.           http://developer.netscape.com/docs/technote/java/getresource/getresource.html
  3453.      Internet Explorer does not seem to have these restrictions.
  3454.  
  3455.      One final "gotcha" is that jpgStream.available() (wrongly) returns 1
  3456.      when .gif files in the .jar file are compressed! Some people now create
  3457.      a .jar file in two steps, essentially:
  3458.  
  3459.              jar cvf x.jar *.class
  3460.              jar uf0 x.jar *.gif
  3461.  
  3462.      This ensures .gifs are not compressed, and hence that available()
  3463.      doesn't lie to you. David Alex Lamb stumbled onto this after wondering
  3464.      why his .gif files looked bad, then realized that compression of a .gif
  3465.      might throw away detail. The conjecture is that available() returns 1
  3466.      because it has to block to do uncompression.
  3467.  
  3468.  10. (Sect. 7) How do I execute a command from Java? How do I do I/O
  3469.      redirection in Java using exec()?
  3470.  
  3471.      [*] See the answer to Question 18.7.
  3472.  
  3473.  11. (Sect. 7) I used a C program to write a binary file. When I instantiate
  3474.      a DataInputStream on the file in Java, and try to readInt, I do not get
  3475.      the correct numbers. Why is this?
  3476.  
  3477.      [*] Java does everything in network byte order (big-endian order), as
  3478.      do many computers including Motorola, and SPARC. The Intel x86 uses
  3479.      little-endian order in which the 4 bytes of an int are stored least
  3480.      significant first. Rearranging the bytes on the way in will get you the
  3481.      results you need. This is only necessary when the file was written by a
  3482.      non-Java program on a little-endian machine such as a PC.
  3483.  
  3484.      The following code will byte-swap little-endian integers into network
  3485.      standard order:
  3486.  
  3487.      public int swap(int i) {
  3488.          int byte0 = i & 0xff;
  3489.          int byte1 = (i>>8) & 0xff;
  3490.          int byte2 = (i>>16) & 0xff;
  3491.          int byte3 = (i>>24) & 0xff;
  3492.          // swap the byte order
  3493.          return (byte0<<24) | (byte1<<16) | (byte2<<8) | byte3;
  3494.      }
  3495.  
  3496.  
  3497.      Alternatively, the following code assembles bytes from a byte array
  3498.      that is in big-endian order (as used by Java) into an int:
  3499.  
  3500.      byte[] bytes = ... // whatever
  3501.      int start_index = ... // wherever
  3502.  
  3503.      int value = 0;
  3504.      for ( int i = start_index; i < start_index+4; ++i ) {
  3505.          value = ( value << 8 ) | ( bytes[i] & 0xFF );
  3506.      }
  3507.  
  3508.  
  3509.      If the bytes are in little-endian order, just change the "for"
  3510.  
  3511.      for ( int i = start_index+3; i >= start_index; --i )
  3512.  
  3513.  
  3514.      And this code will assemble a double that has been written in reverse
  3515.      byte order:
  3516.  
  3517.        byte[] gnol = new byte[8];
  3518.        stream.read(gnol);
  3519.  
  3520.        long l = (
  3521.                   ( (gnol[7] & 0xff) << 56) |
  3522.                   ( (gnol[6] & 0xff) << 48) |
  3523.                   ( (gnol[5] & 0xff) << 40) |
  3524.                   ( (gnol[4] & 0xff) << 32) |
  3525.                   ( (gnol[3] & 0xff) << 24) |
  3526.                   ( (gnol[2] & 0xff) << 16) |
  3527.                   ( (gnol[1] & 0xff) <<  8) |
  3528.                     (gnol[0] & 0xff)
  3529.                 );
  3530.  
  3531.        double d = Double.longBitsToDouble(l);
  3532.  
  3533.  
  3534.  12. (Sect. 7) How do I make I/O faster? My file copy program is slow.
  3535.  
  3536.      [*] This is the purpose of BufferedInputStream. It is a flaw in Java
  3537.      that buffered I/O is not the default, with a flag or different
  3538.      constructor to turn it off. I/O is the second worst designed package in
  3539.      Java, after the Date class. ,
  3540.  
  3541.  13. (Sect. 7) How do I do formatted I/O of floating point numbers?
  3542.  
  3543.      [*] Use the class java.text.NumberFormat.
  3544.  
  3545.      Or use http://www.newbie.net/sharky/lava/. Or use Cay Horstmann's
  3546.      http://www.horstmann.com/corejava/Format.java
  3547.      Although many utilities claim to handle all varieties of C's printf, as
  3548.      far as has been found, this is the only one to correctly handle the
  3549.      equivalent of %e in printf.
  3550.  
  3551.      See also the standard packages java.text.DecimalFormat and
  3552.      java.text.NumberFormat
  3553.  
  3554.  14. (Sect. 7) How do I read numbers in exponential format in Java?
  3555.  
  3556.      [*] The program below (written by Steve Chapel) uses StreamTokenizer to
  3557.      read data from the standard input and recognizes doubles in exponential
  3558.      format (e.g. -1.23e-45).
  3559.  
  3560.      import java.io.*;
  3561.  
  3562.      public class ReadExponential {
  3563.          public static void main(String argv[]) {
  3564.              DataInputStream in = new DataInputStream(System.in);
  3565.              StreamTokenizer st = new StreamTokenizer(in);
  3566.              try {
  3567.                  while (st.nextToken() != StreamTokenizer.TT_EOF) {
  3568.                      switch (st.ttype) {
  3569.  
  3570.         case StreamTokenizer.TT_NUMBER:
  3571.                   double num = st.nval;
  3572.                   int exp = 0;
  3573.                   st.ordinaryChars('\0', ' ');
  3574.                   st.nextToken();
  3575.                   st.whitespaceChars('\0', ' ');
  3576.                   if (st.ttype == StreamTokenizer.TT_WORD &&
  3577.                       Character.toUpperCase(st.sval.charAt(0)) == 'E') {
  3578.                       try {
  3579.                          exp = Integer.parseInt(st.sval.substring(1));
  3580.                       } catch (NumberFormatException e) {
  3581.                          st.pushBack();
  3582.                       }
  3583.                   } else if (st.ttype < 0 || st.ttype > ' ')
  3584.                       st.pushBack();
  3585.                   System.out.println("Num " + num * Math.pow(10, exp));
  3586.                   break;
  3587.          case StreamTokenizer.TT_WORD:
  3588.                   System.out.println("Word " + st.sval);
  3589.                   break;
  3590.          default:
  3591.                   System.out.println("Char '" + (char) st.ttype + "'");
  3592.                   break;
  3593.               } // end switch
  3594.           }  // end while
  3595.         } catch (IOException e) {
  3596.           System.out.println("IOException: " + e);
  3597.         }
  3598.       } // end main
  3599.      }
  3600.  
  3601.  
  3602.  15. (Sect. 7) I'm trying to read in a character from a text file using the
  3603.      DataInputStream's readChar() method. However, when I print it out, I
  3604.      get ?'s.
  3605.  
  3606.      [*] Remember that Java characters are 16-bit Unicode characters, while
  3607.      many hosts systems store characters as 8-bit ASCII characters.
  3608.      Therefore, to read individual chacters from a text file, you need to
  3609.      ensure the proper conversion. The proper way to do this is to use an
  3610.      InputStreamReader, which converts from 8 to 16 bit streams:
  3611.  
  3612.      FileInputStream fis = new FileInputStream("myfile.txt");
  3613.      InputStreamReader isr = new InputStreamReader(fis);
  3614.      char c3 = (char) isr.read();
  3615.  
  3616.      The less-favored way (because it is not so portable, as the encodings
  3617.      translation is not done) is just to read a byte and cast it into a
  3618.      character:
  3619.  
  3620.      FileInputStream fis = new FileInputStream("myfile.txt");
  3621.      DataInputStream dis = new DataInputStream(fis);
  3622.      char c1 = (char) dis.readByte();
  3623.  
  3624.  
  3625.  16. (Sect. 7) How do I delete a directory in Java?
  3626.  
  3627.      [*] JDK 1.0 did not support directory removal. JDK 1.1 supports
  3628.      directory removal with the method:
  3629.           public boolean delete() in class java.io.File
  3630.  
  3631.      Make sure you don't have any open streams in the directory you're
  3632.      trying to remove. Do a close() on all streams, even if the underlying
  3633.      file is gone.
  3634.  
  3635.  17. (Sect. 7) How do I tell how much disk space is free in Java?
  3636.  
  3637.      [*] There currently aren't any good Java APIs for system introspection.
  3638.      There is no Java way to control processes, or look at system resources.
  3639.      You can use Runtime.getRuntime().exec() to do "df" on unix or "dir" on
  3640.      Windows right now.
  3641.  
  3642.      Alternatively, check out JConfig:
  3643.      http://www.tolstoy.com/samizdat/jconfig.html
  3644.      JConfig is a cross-platform library that fills in many of the gaps in
  3645.      the core Java API, and makes it possible to work with files, processes,
  3646.      file types, video monitors, etc. in a much more Windows- and
  3647.      Mac-friendly manner.
  3648.  
  3649.  18. (Sect. 7) How do I get a directory listing of the root directory C:\ on
  3650.      a PC?
  3651.  
  3652.      [*] The obvious approach of calling File.list("C:\"); does not work.
  3653.      There are two reasons why this fails. First, slash is an escape
  3654.      character in Java, so if you want a literal slash, you have to repeat
  3655.      it. Second, you need to give the name of the directory, i.e. dot.
  3656.      Putting this together, either of the following calls will work
  3657.  
  3658.      File.list("C:\\.");
  3659.  
  3660.  
  3661.      or
  3662.  
  3663.      File.list("C:/.");
  3664.  
  3665.  
  3666.      Note: a file separator of "/" works just as well as "\" in most Windows
  3667.      programs and library calls. It is an artifact of DOS's origin's as a
  3668.      ripped-off port of CP/M. When Microsoft bought the rights to DOS from
  3669.      Seattle Computer Products (what, you didn't know Microsoft didn't
  3670.      develop DOS? They didn't even own the rights to DOS at the time the
  3671.      contracted with IBM to supply DOS for the PC) they were buying software
  3672.      which was an unauthorized port of the CP/M operating system.
  3673.  
  3674.      CP/M didn't have directories, so it didn't use pathname separators. The
  3675.      forward slash "/" was already used for giving options to CP/M commands,
  3676.      so "\" was pressed into service as the DOS pathname separator, but the
  3677.      DOS shell was taught to understood "/" for compatibility with other
  3678.      OS's. See also JConfig in Q6.15.
  3679.  
  3680.  19. (Sect. 7) What is the difference between the various ZIP formats: ZIP,
  3681.      GZIP, and PKZIP?
  3682.  
  3683.      [*] Zip is an archive file format, popularized on PCs, that contains
  3684.      multiple compressed files.
  3685.      GZIP comes from Gnu. It is essentially a one file subset of the Zip
  3686.      format. You can't put a whole directory into a GZIP archive, just a
  3687.      single file. It's intended for compressing a tarball of many files.
  3688.      PKZIP is a set of commercially available programs that create Zip
  3689.      files. All three use the deflate compression format, which is based on
  3690.      the LZ77 algorithm. This compression is also used by the ZLIB library
  3691.      and hence the PNG graphics file format (which uses ZLIB). PNG -
  3692.      Portable Network Graphics - provides a patent-free replacement for GIF
  3693.      and TIFF.
  3694.  
  3695.      An alternative compression technology, LZW compression, is encumbered
  3696.      by Unisys's patent. LZW is used in GIF files and by the Unix compress
  3697.      command. Luckily, as well as being free from patent restrictions, LZ77
  3698.      also gives better compression than LZW. LZW is the initial letters of
  3699.      the last names of the three computer scientists who developed the
  3700.      algorithm (Lempel, Ziv, Welch).
  3701.  
  3702.      The basic classes (all in java.util.zip) that read LZ77 Zip format are
  3703.      Deflater and Inflater. These are used by the stream classes
  3704.      DeflaterOutputStream and InflaterInputStream. The java.util.zip classes
  3705.      GZIPInputStream and ZipInputStream inherit from InflaterInputStream.
  3706.  
  3707.      PKZIP is a commercial program for DOS, Windows, and OS/2, sold by
  3708.      PKWARE Their FAQ, at http://www.pkware.com/zipgfaq.html, specifically
  3709.      says
  3710.           "Because PKWARE has dedicated the .ZIP file format to the public
  3711.           domain, it is possible for other people to write programs which
  3712.           can read .ZIP files. NOTE THAT THE PKZIP, PKUNZIP, PKSFX PROGRAMS
  3713.           AND THEIR ASSOCIATED SOURCE CODE AND SUPPORT PROGRAMS ARE THE
  3714.           EXCLUSIVE PROPERTY OF PKWARE INC. AND ARE NOT PUBLIC DOMAIN
  3715.           SOFTWARE PROGRAMS.
  3716.  
  3717.      The "other people" PKZIP's FAQ refers to is the InfoZIP project, a
  3718.      group of public-minded programmers spread over the world producing free
  3719.      software that works on most ANSI C compilers and platforms. See
  3720.           http://www.cdrom.com/pub/infozip/.
  3721.  
  3722.      Jar files are in ZIP format, but are not as complete as a full
  3723.      filesystem archive format since file permissions are not saved. Some
  3724.      versions of WinZip are known to be inadequate for processing the full
  3725.      PKZIP format. Use InfoZIP instead.
  3726.  
  3727.  20. (Sect. 7) How can I use characters other than ASCII in Java?
  3728.  
  3729.      [*] Search for the article titled "Adding Fonts to the Java Runtime" or
  3730.      visit:
  3731.      http://java.sun.com/products/jdk/1.2/docs/guide/internat/fontprop.html
  3732.  
  3733.      The article explains how to add fonts to Sun's JDK 1.2 using the
  3734.      font.properties file. [If anyone has summarised the information, please
  3735.      send it in].
  3736.  
  3737.  21. (Sect. 7) I did a read from a Buffered stream, and I got fewer bytes
  3738.      than I specified.
  3739.  
  3740.      [*] This is the way that BufferedInputStream works up to and including
  3741.      the current release. The behavior is so unintuitive that it really
  3742.      represents a bug. Javasoft has "resolved" the bug by writing comments
  3743.      in the program so that the broken behavior is in the range of legal
  3744.      outcomes. Ugh.
  3745.  
  3746.      When you instantiate a buffered input stream, you can specify the size
  3747.      of buffer it should use. Let's call this the internal buffer. When you
  3748.      call read() you can say how many bytes to read. Let's call this the
  3749.      request. If the request is smaller than the internal buffer and not a
  3750.      multiple of the internal buffer, then the last read returns only the
  3751.      odd bytes left in the internal buffer! The more reasonable and
  3752.      intuitive behavior would be for the internal buffer to be refilled, so
  3753.      that the whole request can be granted.
  3754.  
  3755.      For example, if you create a BufferedInputStream with an internal
  3756.      buffer of 1000 bytes, and try to read 512 byte chunks, your first read
  3757.      will return 512 bytes, but your second read will only return
  3758.      (1000-512), or 488, bytes. (Assuming that the file has at least that
  3759.      many bytes in it). The following code illustrates the problem.
  3760.  
  3761.      // troubleshooting by Tov Are Jacobsen
  3762.      import java.io.*;
  3763.      class filebug {
  3764.          public static void main(String args[])
  3765.                        throws FileNotFoundException, IOException  {
  3766.          BufferedInputStream bis =
  3767.             new BufferedInputStream(
  3768.             new FileInputStream("test.txt"), 1000 );
  3769.          byte[] buf = new byte[2000];
  3770.          int numread;
  3771.          System.out.println( "Available: "+bis.available() );
  3772.          while (true) {
  3773.              numread = bis.read(buf,0,512);
  3774.              if (numread<0) break;
  3775.              System.out.println( "got "+numread
  3776.                                 +", avail:"+ bis.available());
  3777.          }
  3778.        }
  3779.      }
  3780.  
  3781.  
  3782.      Of course, a valid reason for getting less than you asked for is that
  3783.      you asked for more data than is actually available in the Stream, e.g.
  3784.      you requested 512 bytes from a file that only contains 40 bytes. In
  3785.      general, there are no guarantees about how much data is returned for a
  3786.      given buffered input stream read request. To avoid this problem, push a
  3787.      DataInputStream on top of your buffered stream. Then you can call
  3788.      readFully(), which will do what you want.
  3789.  
  3790.      A similar "got less than I asked for" occurs when reading a socket.
  3791.      Network protocols frequently packetize data and send it across in
  3792.      bursts. Nothing is lost of course, and you are always told how many
  3793.      bytes you actually got. You will get the remaining bytes on a
  3794.      subsequent read. This happens regardless of the language used. Be sure
  3795.      to check the "amount of data returned" when using the read(byte[], int,
  3796.      int) method of BufferedInputStream, or when reading from a socket.
  3797.  
  3798.      Another problem with java.io.InputStream.read(byte[], int, int) is that
  3799.      it catches and ignores IOExceptions. Instead, these exceptions should
  3800.      be passed on to the caller. Ace programmer Jef Poskanzer, jef@acme.com,
  3801.      has a version to do this at
  3802.      http://www.acme.com/java/software/Acme.Utils.html. See Jef's read() and
  3803.      readFully() routines.
  3804.  
  3805.  22. (Sect. 7) How do I redirect the System.err stream to a file?
  3806.  
  3807.      [*] You cannot assign a new FileOutputStream to System.err, as it is
  3808.      final. Instead use the System.setErr() library call, like this:
  3809.  
  3810.      FileOutputStream err = new FileOutputStream("stderr.log");
  3811.      PrintStream errPrintStream = new PrintStream(err);
  3812.      System.setErr(errPrintStream);
  3813.  
  3814.  
  3815.      This was introduced with JDK 1.1. There is also a corresponding setIn()
  3816.      for redirecting standard in, and a setOut() for standard out.
  3817.  
  3818.      Note that you will get a compiler warning about a deprecated construct
  3819.      when you do this. PrintStreams are deprecated in favor of PrintWriters,
  3820.      which handle Unicode properly. The PrintStream is marked as deprecated
  3821.      by marking all its constructors as deprecated. There is no way to
  3822.      create the PrintStream needed to redirect System.err or System.out
  3823.      without triggering the deprecated warning.
  3824.  
  3825.  23. (Sect. 7) What are the values for the Unicode encoding schemes?
  3826.  
  3827.      [*] If you review the String constructor with this signature
  3828.  
  3829.          String(byte[] bytes, String encoding)
  3830.  
  3831.      you can see that one argument is a value for the encoding scheme that
  3832.      the conversion of 8-bit bytes to 16-bit Unicode chars is to use.
  3833.  
  3834.      There are three: "Unicode", "UnicodeBig" and "UnicodeLittle". The first
  3835.      one expects the first two bytes of your data to be a Byte Order Mark,
  3836.      FEFF or FFFE, which specifies whether the data is in little-endian or
  3837.      big-endian order. If there isn't a BOM but you already know the
  3838.      endianness, you can use "UnicodeBig" or "UnicodeLittle" directly.
  3839.  
  3840.      There is also a Sun document at
  3841.      http://java.sun.com/products/jdk/1.1/docs/guide/intl/encoding.doc.html
  3842.      with some related information (not much).
  3843.  
  3844.      There is another Sun document at
  3845.      http://java.sun.com/products/jdk/1.1/intl/html/intlspec.doc7.html which
  3846.      shows the table of encodings. There is a new system property called
  3847.      "file.encoding" which translates between codes known to Java like
  3848.      "Cp1252", and locale encoding names like "Windows Western Europe /
  3849.      Latin-1"
  3850.  
  3851.  24. (Sect. 7) Is there a way to read a char from the keyboard without
  3852.      having to type carriage-return?
  3853.  
  3854.      [*] You can do this in a GUI (e.g. in a text component). There is no
  3855.      pure Java way to do character-by-character I/O without using a GUI.
  3856.  
  3857.                        -------------------------------
  3858.  
  3859. 8. Core Libraries
  3860.  
  3861.   1. (Sect. 8) I can't seem to change the value of an Integer object once
  3862.      created.
  3863.  
  3864.      [*] Correct. Integer (Float, Double, etc) are intended as an object
  3865.      wrapper for a specific value of a number, not as a general-purpose way
  3866.      of shipping a primitive variable around as an Object. If you need that
  3867.      it's easy enough to create: class General { public int i; }
  3868.  
  3869.   2. (Sect. 8) How do I print from a Java program?
  3870.  
  3871.      [*] Use the Toolkit.getPrintJob() method
  3872.  
  3873.      Component c = this.getParent();
  3874.      while (c!=null && !(c instanceof Frame))
  3875.          c=c.getParent();
  3876.      // With a JComponent use   c=getTopLevelAncestor();
  3877.  
  3878.      PrintJob pj = getToolkit().getPrintJob((Frame) c, "test", null);
  3879.      Graphics pg = pj.getGraphics();
  3880.      printAll(pg);
  3881.      pg.dispose();
  3882.      pj.end();
  3883.  
  3884.  
  3885.      This feature was introduced with JDK 1.1. A common place to put this is
  3886.      in the code that handles a button press. Printing from an untrusted
  3887.      applet is subject to a check from the SecurityManager.
  3888.  
  3889.      The JDK 1.1 printing API is more a screen hardcopy facility than a full
  3890.      blown publishing and illustration hardcopy API. JDK 1.2 offers a more
  3891.      full-featured printing API.
  3892.  
  3893.      If you simply want to print text, then write it to a file and print the
  3894.      file. Or open a filename that corresponds to the printer. On Windows,
  3895.      that is "LPT1" and the code looks like:
  3896.  
  3897.      try {
  3898.          FileOutputStream fos = new FileOutputStream("LPT1");
  3899.          PrintStream ps = new PrintStream(fos);
  3900.                  ps.print("Your string goes here");
  3901.                  ps.print("\f");
  3902.                  ps.close();
  3903.      } catch (Exception e) {
  3904.          System.out.println("Exception occurred: " + e);
  3905.      }
  3906.  
  3907.  
  3908.      The final formfeed is needed by windows to start the printjob.
  3909.  
  3910.   3. (Sect. 8) What are the properties that can be used in a PrintJob?
  3911.  
  3912.      [*] The properties are
  3913.         o awt.print.destination - can be "printer" or "file"
  3914.         o awt.print.printer - printer name
  3915.         o awt.print.fileName - name of the file to print
  3916.         o awt.print.numCopies - obvious
  3917.         o awt.print.options - options to pass to the print command
  3918.         o awt.print.orientation - can be "portrait" or "landscape"
  3919.         o awt.print.paperSize - can be "letter","legal","executive" or "a4"
  3920.      paperSize=letter, and numCopies=1.
  3921.  
  3922.      You can search for info like this by joining the Java Developer
  3923.      Connection (it's free) at http://java.sun.com/jdc.
  3924.  
  3925.      and doing a search for "PrintJob".
  3926.  
  3927.   4. (Sect. 8) Is there any package in Java to handle HTML?
  3928.  
  3929.      [*] See the answer to Question 13.14.
  3930.  
  3931.   5. (Sect. 8) Why don't Dialogs work the way I want them to?
  3932.  
  3933.      [*] Modal dialogs (dialog windows that stay up until you click on them)
  3934.      are buggy in many browsers and in the 1.0.2 JDK. One bug is that the
  3935.      dialog is not necessarily put on top when it is displayed. Most of the
  3936.      modal dialog bugs are fixed in JDK 1.1.
  3937.  
  3938.   6. (Sect. 8) Where can I find information about the sun.* classes in the
  3939.      JDK?
  3940.  
  3941.      [*] You're not supposed to. Those classes are only to support functions
  3942.      in the java.* hierarchy. They are not part of the API, and won't be
  3943.      present in Java systems from non-Sun vendors. Some people have
  3944.      reverse-engineered the code and published an API for these classes but
  3945.      you use it at your own risk, and it may change without warning.
  3946.  
  3947.      Worst of all, those programs will not have the portability of true Java
  3948.      but will only run on Sun JDKs. For the same reason you shouldn't use
  3949.      classes outside the java.* packages when using JDKs from other vendors.
  3950.  
  3951.      If you still insist on going ahead, check these URLs:
  3952.      http://java.sun.com/products/api-overview/index.html
  3953.      http://www.parmly.luc.edu/javaudio/
  3954.      http://www.users.interport.net/~mash/javamidi.html
  3955.  
  3956.   7. (Sect. 8) How do you read environment variables from with a Java
  3957.      program?
  3958.  
  3959.      [*] Environment variables are not used in Java, as they are not
  3960.      platform-portable. The Mac doesn't have environment variables, for
  3961.      example. A Windows 95 application not started from a DOS window does
  3962.      not have environment variables. Use properties instead. It was a design
  3963.      error in JDK 1.0 that programmers had to set the CLASSPATH environment
  3964.      variable. This should have been set in a property file
  3965.  
  3966.      Create your own properties file (see java.util.Properties) or specify
  3967.      them with the -D option when you invoke the interpreter or JRE.
  3968.      Additionally, on some systems you can set a property from the command
  3969.      invocation line like this:
  3970.  
  3971.      java -Dfoo=$foo MyClass (Unix)
  3972.  
  3973.      or
  3974.  
  3975.      java -Dfoo=%foo% MyClass (Win95/NT)
  3976.  
  3977.      This sets the "foo" property to the value of the environment variable
  3978.      foo, and makes it available in the System properties. Make sure you do
  3979.      not leave any spaces after the -D or around the = sign. Inside the
  3980.      program you get the value with:
  3981.  
  3982.      String env = System.getProperty("foo");
  3983.  
  3984.      More simply, just put the environment variable on the command line and
  3985.      read it as arg[0].
  3986.  
  3987.      java MyClass %FOO% ; Win32
  3988.          java MyClass $FOO ; Unix
  3989.  
  3990.  
  3991.      Finally, you could execute a Runtime process to get the environment
  3992.      variables if you are on a platform that has them.
  3993.  
  3994.      import java.io.*;
  3995.      import java.util.Properties;
  3996.  
  3997.      public class Main {
  3998.          public static void main(String[] argv) {
  3999.              Properties envVars = new Properties();
  4000.  
  4001.              try {
  4002.                envVars.load(   // use "set" on Windows
  4003.                      Runtime.getRuntime().exec("/bin/env").getInputStream());
  4004.              } catch (Throwable t) {t.printStackTrace();}
  4005.  
  4006.              System.out.println("\n\n" + argv[0]
  4007.                               + " = <" + envVars.get(argv[0]) + ">");
  4008.          }
  4009.      }
  4010.  
  4011.      This is not a Pure Java approach as it builds platform-specific
  4012.      knowledge into the program. See Question 10.6 for more details. On
  4013.      Unix, the command that prints environment variables is "/usr/bin/env".
  4014.      On Windows95, it is "set"
  4015.  
  4016.   8. (Sect. 8) How do I get Java talking to a Microsoft Access database?
  4017.  
  4018.      [*] Use the JDBC-ODBC bridge. It is not especially challenging to set
  4019.      up, but it does require painstaking attention to detail. There is a
  4020.      step-by-step example in the van der Linden text "Just Java" mentioned
  4021.      in the sponsorship section of this document.
  4022.  
  4023.      Note that the Microsoft version of the Java kit does not support
  4024.      JDBC-ODBC access because it uses a non-standard native code interface.
  4025.      The JDBC FAQ can be found at
  4026.      http://java.sun.com/products/jdbc/jdbc-frequent.html
  4027.  
  4028.   9. (Sect. 8) I can't seem to change the current working directory.
  4029.  
  4030.      [*] Correct. This missing functionality is an oversight that we hope
  4031.      will be corrected in the future. The bug id is 4156278, please feel
  4032.      free to join the JDC, and vote to have this (or any other) fixed.
  4033.      Changing the user.dir property merely changes the text property, not
  4034.      the underlying reality that it is supposed to reflect.
  4035.  
  4036.      There are several workarounds.
  4037.         o Run your java app from a .bat or .sh file and do the "cd" in that
  4038.           (before you run your java app), assuming that all the external
  4039.           processes you need to exec can be run from the same directory.
  4040.         o Do: exec("cd /home/wherever; externalApp.exe") on unix, (there
  4041.           doesn't seem to be an equivalent on NT).
  4042.         o Instead of running the .exe directly, run (or write on the fly) a
  4043.           .bat or .sh file that does the cd and then runs the .exe for you
  4044.           (this could well create trouble with getting back the correct
  4045.           return status)
  4046.  
  4047.  10. (Sect. 8) How do I create a Vector of ints?
  4048.  
  4049.      [*] ints are primitive types and hence can't be stored by the Vector
  4050.      class, which stores objects. You'll need to wrap the ints. Try this:
  4051.  
  4052.      int i =7;
  4053.      Vector holdsInts = new Vector(5,1);
  4054.  
  4055.      holdsInts.addElement(new Integer(i));
  4056.      int j = ((Integer)holdsInts.elementAt(0)).intValue();
  4057.  
  4058.  
  4059.  11. (Sect. 8) I have several worker threads. I want my main thread to wait
  4060.      for any of them to complete, and take action as soon as any of them
  4061.      completes. I don't know which will complete soonest, so I can't just
  4062.      call Thread.join on that one. How do I do it?
  4063.  
  4064.      [*] You need to use the wait/notify mechanism to allow any of the
  4065.      worker threads to wake up your main thread when the worker has
  4066.      completed.
  4067.  
  4068.  12. (Sect. 8) How do I get random numbers?
  4069.  
  4070.      [*] If you just need a quick random double between 0.0 and just less
  4071.      than 1.0
  4072.  
  4073.      double myrandom = Math.random(); // [0,1)
  4074.  
  4075.  
  4076.      The notation "[0,1)" is common math notation for "zero to .9999999 etc"
  4077.      The Sun documents say this returns 0.0 to 1.0, but inspection of the
  4078.      source shows they are wrong. However, due to the inherent inaccuracies
  4079.      of floating point arithmetic, multiplying N by 0.999999 etc can result
  4080.      in an answer of N, not N * .999999. So watch out when N is big.
  4081.  
  4082.      JDK 1.2 adds another version of nextInt that accepts a parameter for
  4083.      returning ranged random numbers.
  4084.  
  4085.      Where things get trickier is when you use JDK 1.1 and want an int in a
  4086.      certain range, say 1 to 6 to simulate the throw of a die or 1 to 52 to
  4087.      represent a playing card. Class Random has a nextInt method that will
  4088.      return any integer:
  4089.  
  4090.      import java.util.Random;
  4091.      Random r = new Random();
  4092.      int i = r.nextInt();
  4093.  
  4094.  
  4095.      However, that has an (almost) 50% chance of being negative, and it
  4096.      doesn't come from the right range. So you just take the abs() value and
  4097.      then mod it into the right range:
  4098.  
  4099.      int dice_throw = 1 + Math.abs(i) % 6;
  4100.  
  4101.  
  4102.      Except, the abs() method fails gracelessly in the presence of the
  4103.      Integer.MIN_VALUE (it returns the same, negative, result!). So it is
  4104.      better to AND to get the non-negative value: In general, to get a
  4105.      random int between high and low limits (inclusive):
  4106.  
  4107.      java.util.Random r = new java.util.Random();
  4108.      int j = (r.nextInt() & Integer.MAX_VALUE) % (high-low+1) + low;
  4109.  
  4110.  
  4111.      The sentence above states "(almost) 50% chance" because there is one
  4112.      more value in the negative integers than in the positive integers in
  4113.      two's complement arithmetic as used by Java. For most purposes, the
  4114.      bias introduced will be insignificant, but we "and" the nextInt() to
  4115.      convert it to zero. Sure, it's unlikely to occur, but you don't want
  4116.      the reactor going critical just because you missed this case while
  4117.      testing.
  4118.  
  4119.      A worse problem is that with the algorithm used, the low order bits are
  4120.      significantly less random than the higher order bits. And the low order
  4121.      bits are precisely the ones you get when you do a (mod 2^n) operation.
  4122.      You may consider using java.security.SecureRandom which provides much
  4123.      better randomness by using a Cryptographic hash, although it is much
  4124.      more expensive to compute.
  4125.  
  4126.  13. (Sect. 8) What does "deprecated" mean? I got this in a compiler error
  4127.      message.
  4128.  
  4129.      [*] The compiler will flag a now-obsolete API as "deprecated". The word
  4130.      means "officially disapproved of". Compile again with the
  4131.      "-deprecation" option to see what is deprecated. In almost all cases,
  4132.      the old API has been replaced by a new one. Update your code to use the
  4133.      new one.
  4134.  
  4135.      An example of using a deprecated API is calling component.size(). That
  4136.      has been replaced by component.getSize().
  4137.  
  4138.  14. (Sect. 8) Where/why should I use the Enumeration interface?
  4139.  
  4140.      [*] It's a very convenient way to step through some of the library data
  4141.      structures, such as HashTable, Vector, and ZipFile. It is thread safe.
  4142.      If you're looking at an element in one thread while another thread is
  4143.      trying to delete it, it won't half vanish.
  4144.  
  4145.      Here's how you might look at every file in a ZIP file:
  4146.  
  4147.      ZipFile z = new ZipFile("foo.zip");
  4148.      Enumeration e = null;
  4149.      for (e=z.entries(); e.hasMoreElements(); ) {
  4150.         ZipEntry ze = (ZipEntry)e.nextElement();
  4151.         System.out.println("got " + ze.getName() );
  4152.      }
  4153.  
  4154.  
  4155.      And here's how you might look at all the tokens in a String:
  4156.  
  4157.      StringTokenizer tokens =
  4158.          new StringTokenizer (SomeArbitraryString, "\n", false);
  4159.  
  4160.      Enumeration enum = tokens.elements();
  4161.      while enum.hasMoreElements()
  4162.          System.out.println(enum.nextElement());
  4163.  
  4164.      You should look for opportunities in your own data structures to
  4165.      implement Enumeration anywhere where the structure has repeated
  4166.      elements.
  4167.  
  4168.  15. (Sect. 8) Which version of WinZip is compatible with java.util.zip?
  4169.  
  4170.      [*] You need WinZip version 6.2 or later. Version 6.1 or earlier is not
  4171.      good enough. WinZip can be downloaded from
  4172.      http://www.winzip.com/download.cgi. The pkzip software works fine.
  4173.      Infozip is better than WinZip because it lacks the winzip "feature" of
  4174.      failing to recreate directories unless given a special option. Use
  4175.      Infozip.
  4176.  
  4177.  16. (Sect. 8) How can Java access other fonts on my system?
  4178.  
  4179.      [*] You do it by editing the fontnames in the font.properties file in
  4180.      the lib directory of your JDK release. Watch out for program
  4181.      portability when you do this.
  4182.  
  4183.      For more details, check the website
  4184.      http://www.alumni.caltech.edu/~dank/javafont.htm and the JavaSoft site
  4185.      at http://java.sun.com/products/jdk/1.1/docs/guide/intl/fontprop.html
  4186.      They have lots of information on this.
  4187.  
  4188.  17. (Sect. 8) How can I trap Control-C in Java?
  4189.  
  4190.      [*] Control-C is used on some OS's to break into a running program
  4191.      interactively and terminate it. On Unix Control-C is sent to the
  4192.      process as a signal. If a C program declares a handler for that signal,
  4193.      the program will be able to continue even if Control-C is sent to it.
  4194.  
  4195.      Control-C is not a Java concept, and there is no way to do this
  4196.      portably.
  4197.      On Unix you can write the signal handler in C, and impose the handler
  4198.      by calling the C routine through the Java Native Interface.
  4199.      On Win32 in a GUI a KeyPressedListener will see a control-C as
  4200.      java.awt.event.KeyEvent[KEY_PRESSED,keyCode=67,modifiers=Ctrl]
  4201.      On Win32 in a command line app you can't read a control-C in Java
  4202.      because it is sent to the process as a signal (as with Unix).
  4203.      Instead of interposing a signal handler thru JNI, you could launch java
  4204.      from perl or a shell script which is capable of doing this.
  4205.      Alternatively, use javaw to launch the JVM so that it has no keyboard
  4206.      which can ctrl-C it.
  4207.  
  4208.  18. (Sect. 8) How do you parse commandline arguments to a Java program?
  4209.  
  4210.      [*] Perhaps surprisingly, commandline arguments are not encouraged, as
  4211.      they make a program not 100% pure Java. The reason is that some systems
  4212.      like MacOS don't normally have a command line or command-line
  4213.      arguments. Consider using properties instead so that your programs fit
  4214.      more naturally into the environment.
  4215.  
  4216.      If you must use command-line arguments, have them comply with the POSIX
  4217.      conventions, i.e. they should
  4218.         o use a "-" instead of a "/"
  4219.         o be case sensitive, and
  4220.         o be concatenatable (-pst == -p-s-t).
  4221.      See
  4222.      http://java.sun.com/docs/books/tutorial/essential/attributes/_posix.html
  4223.  
  4224.      If such arguments are used, it should NOT be up to the invocating
  4225.      application (ie java.exe) to propperly parse them. According to the
  4226.      getopts routine from gnu, getopts is required to know exactly what the
  4227.      usable parameters are before it can properly parse them and create
  4228.      argc/argv.
  4229.  
  4230.      Because of that, it becomes unduly hard for calling programs such as
  4231.      java.exe to properly parse class arguments by themselves. Instead, they
  4232.      should create an argc/argv pair (actually a java specific array
  4233.      dependant on the way in which the method is called) where the number of
  4234.      elements equals the number of text words in the options. Text word
  4235.      means a group of ascii characters outside of quotation marks, not
  4236.      separated by white space. Once these text words are passed to the
  4237.      class, it is up to the class to actually parse them correctly.
  4238.  
  4239.      The text words passed to the class can be parsed however the class
  4240.      author wishes. It is up to the author to correctly parse the options.
  4241.      There are several implementations of getopts which perform such
  4242.      parsing, in C, Perl, and Java. You will find one at
  4243.      http://www.urbanophile.com/arenn/hacking/download.html#getopt
  4244.  
  4245.  19. (Sect. 8) How many threads can I create?
  4246.  
  4247.      [*] By default, on a Win32 machine, each ("native") thread gets one MB
  4248.      (1024*1024 bytes) of stack space reserved for it. The memory is not
  4249.      actually allocated. If it were, you'd run out of memory with dozens of
  4250.      threads instead of hundreds. The space needs to be reserved as a
  4251.      contiguous block of memory so the stack can grow as needed.
  4252.  
  4253.      Under Win32, the max amount of memory is 2GB, which corresponds to
  4254.      2,000 threads each reserving 1MB of memory. That's an upper bound; in
  4255.      practice you'd run out of other OS resources before running out of
  4256.      memory. Each thread has some system resources that will be used to
  4257.      manage the thread -- register storage area, thread-local storage, state
  4258.      information, exception condition info, etc.
  4259.  
  4260.      You should design your programs so that you use threads only where
  4261.      necessary. It's almost always a mistake to have one thread per object.
  4262.      Successful programs are much more likely to have 5 threads (or fewer)
  4263.      than 500.
  4264.  
  4265.                        -------------------------------
  4266.  
  4267. 9. Dates and Times
  4268.  
  4269.      Credit to Paul Hill who completely rewrote this section, and to
  4270.      the programmers at IBM who implemented much of the Java Date code,
  4271.      and reviewed this section of the FAQ for accuracy.
  4272.  
  4273.                                java.util.Date
  4274.  
  4275.   1. (Sect. 9) Is Java "Year 2000"-compliant?
  4276.  
  4277.      [*] Java is Y2K compliant in release JDK 1.1.6 and later. See
  4278.      http://www.sun.com/y2000/cpl.html. Prior to this release there were
  4279.      certain corner case bugs that had to be fixed.
  4280.  
  4281.      The Date class, as you can see from the discussion, contains more than
  4282.      enough resolution to represent dates in this century and the next and
  4283.      the last. The SimpleDateFormat when parsing a 2 digit year could cause
  4284.      problems; see discussion below.
  4285.  
  4286.   2. (Sect. 9) What happen to java.util.Date between JDK 1.0 and JDK 1.1?
  4287.  
  4288.      [*] In JDK 1.1 the java.util.Date class was split to provide better
  4289.      support for timezones, and internationalization.
  4290.  
  4291.      The classes specifially related to dates are summarized below:
  4292.  
  4293.             1. The class Date represents a specific instant in time,
  4294.                with millisecond precision.
  4295.             2. The class TimeZone is an abstract class that represents
  4296.                a time zone offset, and also figures out daylight
  4297.                savings time adjustment.
  4298.             3. The class SimpleTimeZone is the only concrete subclass
  4299.                of TimeZone in the JDK.  It is what defines an ordinary
  4300.                timezone with a simple daylight savings and daylight
  4301.                savings time period.
  4302.             4. The class Calendar is an abstract class for converting
  4303.                between a Date object and a set of integer fields such
  4304.                as year, month, day, and hour.
  4305.             5. The class GregorianCalendar is the only concrete
  4306.                subclass of Calendar in the JDK. It does the
  4307.                Date-to-fields conversions for the calendar system in
  4308.                common use.
  4309.             6. The class DateFormat is an abstract class that lets you
  4310.                convert a Date to a printable string with fields in the
  4311.                way you want (e.g. dd/mm/yy or dd.MMM.yyyy).
  4312.             7. The class SimpleDateFormat is the only concrete subclass
  4313.                of DateFormat in the JDK. It takes a format string and
  4314.                either parses a string to produce a date or takes  a
  4315.                date and produces a string.
  4316.  
  4317.      At least one critic has used the term "baroque" when describing the
  4318.      complexities of the Java date related classes, but other critics would
  4319.      spell that "broke". The good news is that as of JDK 1.2 all of the
  4320.      common problems have been corrected and many of the bugs were corrected
  4321.      in 1.1.4 and 1.1.6. Even in 1.1.1, you can avoid most of the most
  4322.      annoying bugs by always keeping in mind which timezone each class is
  4323.      using.
  4324.  
  4325.   3. (Sect. 9) Exactly what is a java.util.Date?
  4326.  
  4327.      [*] A java.util.Date stores a moment in time as a long integer
  4328.      representing the number of milliseconds since 00:00:00 Jan 1, 1970 UTC
  4329.      (Coordinated Universal Time). This zero moment is known as the "Epoch".
  4330.      This is the same Epoch as is used on Unix systems. Dates earlier than
  4331.      the Epoch are represented as negative numbers, counting away from
  4332.      1/1/1970.
  4333.  
  4334.      The scheme is sufficient to represent dates from 292,269,053 B.C. to
  4335.      292,272,993 A.D. (64 bits covers -9,223,372,036,854,775,808 to
  4336.      +9,223,372,036,854,775,807 milliseconds. But note that prior to JDK
  4337.      1.2, a GregorianCalendar will not accept values earlier than 4713 B.C.
  4338.  
  4339.      A java.util.Date is the light-weight object intended to just hold a
  4340.      millisecond value. It is used to hold, communicate and store a moment
  4341.      in time. Other tasks like creating a formated string, or calculating
  4342.      dates are best done using other classes.
  4343.  
  4344.   4. (Sect. 9) Does a java.util.Date really represent the true UTC?
  4345.  
  4346.      [*] No, but it is close enough for most human time-keeping purposes. On
  4347.      most computers, it only represents the time since the epoch as
  4348.      converted from the value on the underlying hardware. If you have
  4349.      hardware that is synchronized with an atomic clock your time is UTC;
  4350.      most hardware assumes a day is 24 hours long, but there have been more
  4351.      than 20 leap seconds added to UTC, since the first one was added in
  4352.      1972.
  4353.  
  4354.   5. (Sect. 9) How do I create a Date object that represents the current
  4355.      time?
  4356.  
  4357.      [*] The default value of a date object is the current time, so the
  4358.      following code creates a date object that contains the current time.
  4359.  
  4360.      Date now = new Date();
  4361.  
  4362.   6. (Sect. 9) I want to create a string that represents a date in a format
  4363.      other than what is returned by java.util.Date.toString() do I have to
  4364.      use a Calendar?
  4365.  
  4366.      [*] No. Instead of creating a Calendar and pulling out all of the
  4367.      appropriate fields and making a string, you could use
  4368.      SimpleDateFormat.format() to create a string.
  4369.  
  4370.   7. (Sect. 9) Why are all the methods in java.util.Date deprecated?
  4371.  
  4372.      [*] Mostly because the original java.util.Date was not completely aware
  4373.      of the timezone and "not amenable to internationalization". To make it
  4374.      timezone aware and internationalizable would have required adding some
  4375.      of the functionality which can now be seen in java.util.Calendar and
  4376.      some of the functionality in java.util.DateFormat. If you find the
  4377.      combination all of the date related classes complex, just be glad they
  4378.      were separated into different classes.
  4379.  
  4380.   8. (Sect. 9) I really don't need a internationalizable, timezone aware,
  4381.      extra flexible formating set of date classes. Is there anything else I
  4382.      can use that stores only a date, and allows me to do some date
  4383.      calculations?
  4384.  
  4385.      [*]You could consider using the BigDate class written by Roedy Green,
  4386.      and available in his very informative glossary (search for BigDate). If
  4387.      you want to store the result in a database as a Date or TimeStamp, you
  4388.      should read the section below on java.sql.Date.
  4389.  
  4390.   9. (Sect. 9) Since the Date( String ) constructor is deprecated what do I
  4391.      use instead?
  4392.  
  4393.      [*] The best choice is to use SimpleDateFormat.parse() to create a
  4394.      java.util.Date object.
  4395.  
  4396.      The Date constructor that accepts a string calls Date.parse( String ).
  4397.      The Date.parse() function had its own rules for converting 2 digit
  4398.      years (it used a 1980 pivot date) and other limitiations which makes it
  4399.      of limited value. Other "features" of Date.parse() that are not
  4400.      supported in SimpleDate have not been missed by many developers.
  4401.  
  4402.  10. (Sect. 9) Since Date(int year, int month, int date) and related
  4403.      constructors are deprecated what do I use instead?
  4404.  
  4405.      [*] The constructor GregorianCalendar(int year, int month, int date) is
  4406.      the newer replacement. Other choices are the Calendar.set( year, month,
  4407.      day ) method. Note that the year in the GregorianCalendar starts at 1
  4408.      A.D., not at 1901 like the old Date constructor.
  4409.  
  4410.  
  4411.                                 java.util.TimeZone
  4412.  
  4413.  11. (Sect. 9) How can I see if my JVM is using the right timezone?
  4414.  
  4415.      [*] The following codes displays the ID of the current default
  4416.      timezone.
  4417.  
  4418.        System.out.println( TimeZone.getDefault().getID() );
  4419.  
  4420.  12. (Sect. 9) The value of TimeZone.getDefault is not what I expected. What
  4421.      is the problem?
  4422.  
  4423.      [*] The value of the default timezone is based on the value of the
  4424.      system property "user.timezone". The JVM  is supposed to set this
  4425.      value. In releases such as JDK 1.1 the value of user.timezone was often
  4426.      not set to anything, so TimeZone.getDefault() used its own built in
  4427.      "fallback" value (the default when there is no default value). In later
  4428.      JDK 1.1 releases and in JDK 1.2 the setting of the value of
  4429.      user.timezone is much better and the "fallback" value is now GMT
  4430.      (Greenwich Mean Time). Up until JDK 1.1.3, the fallback value was "PST"
  4431.      (North American Pacific Timezone).
  4432.  
  4433.  13. (Sect. 9) Do all the standard objects use the same default timezone?
  4434.  
  4435.      [*] Not until JDK 1.2. In JDK 1.1, Date.toString() and Calendar used
  4436.      the value of TimeZone.getDefault() which could often be undefined (see
  4437.      the previous question). In JDK 1.1, The Calendar in a SimpleDateFormat
  4438.      was set to the 1st timezone resource for the locale (for the US this is
  4439.      PST).
  4440.  
  4441.      System.out.println( "Date format TZ = " + TimeZone.getDefault().getID() );
  4442.      sdf = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG );
  4443.      System.out.println( "Date format TZ = " + sdf.getTimeZone().getID() );
  4444.      Calendar cal = Calendar.getInstance();
  4445.      System.out.println( "Calendar TZ = " + cal.getTimeZone().getID() );
  4446.  
  4447.      When run on a system running JDK 1.1.6, NOT in the North American
  4448.      Pacific Time nor in the GMT timezone results in:
  4449.  
  4450.      Timezone default = GMT
  4451.      Date format TZ = PST
  4452.      Calendar TZ = GMT
  4453.  
  4454.      This example shows two bugs, the value of user.timezone is undefined,
  4455.      so its defaulting to GMT (see discussion of TimeZone.getDefault()) and
  4456.      it shows that the DateFormat depends on the 1st locale entry which in
  4457.      this case is PST.
  4458.  
  4459.      If you don't want the DateFormat to use the Locale timezone, see the
  4460.      code provided below.
  4461.  
  4462.  14. (Sect. 9) If I explicitly set the default timezone, don't I need code
  4463.      to choose between (a) the daylight savings version or (b) the standard
  4464.      version of a timezone?
  4465.  
  4466.      [*] No. The ID that you use to select a timezone with
  4467.      TimeZone.getTimeZone refers to a predefined timezone that contains
  4468.      daylight savings information (when applicable). For example, the
  4469.      following code selects the timezone used in New York, USA.
  4470.  
  4471.      // Get the North American Eastern Time definition.
  4472.      TimeZone theTz = TimeZone.getTimeZone( "EST" );
  4473.      // get a really detailed date format and set it to the right timezone
  4474.      DateFormat df = DateFormat.getDateTimeInstance( DateFormat.LONG,
  4475.      DateFormat.LONG );
  4476.      df.setTimeZone( theTz );
  4477.      // create a date in the locale's calendar, set its timezone and hour.
  4478.      Calendar day = Calendar.getInstance();
  4479.      day.setTimeZone( theTz );
  4480.      day.set( 1998, Calendar.FEBRUARY, 1 );
  4481.      day.set( Calendar.HOUR, 12 );
  4482.  
  4483.      // print that date/time and
  4484.      // that date/time 150 full days of milliseconds later.
  4485.      System.out.println( df.format( day.getTime() ) );
  4486.      System.out.println( df.format(
  4487.      new Date( day.getTime().getTime() +    // get the millis
  4488.              150L*24*60*60*1000L ) ) );     // add exactly 150 days of millis
  4489.  
  4490.      Results in:
  4491.  
  4492.      February 1, 1998 12:00:00 PM EST
  4493.      July 1, 1998 1:00:00 PM EDT
  4494.  
  4495.      Notice that this example selected something refered to as "EST", but
  4496.      that this TimeZone was aware of the daylight savings time change and
  4497.      either printed as "EST" or "EDT".
  4498.  
  4499.      The confusion is reduced in JDK 1.2, you can use longer TimeZone IDs
  4500.      each maps to its own set of text resources. For example the following
  4501.      IDs are 5 hour West of GMT and have various DST rules:
  4502.      "America/Nassau", "America/Montreal", "America/Havana",
  4503.      "America/Port-au-Prince", "America/Grand_Turk", "America/New_York" and
  4504.      "EST".
  4505.  
  4506.      You can look at a list of other timezone names and offsets in the file
  4507.      $JAVAHOME/src/java/util/TimeZone.java
  4508.  
  4509.  15. (Sect. 9) How do I create my own Time Zone to apply to dates?
  4510.  
  4511.      [*] You can create a TimeZone object with the GMT offset of your
  4512.      choice. The following code creates British Time, a timezone that was
  4513.      not defined in 1.1.
  4514.  
  4515.      britTime = new SimpleTimeZone(0*ONE_HOUR, "Europe/London" /*GMT/BST*/,
  4516.          Calendar.MARCH,  -1, Calendar.SUNDAY /*DOW_IN_DOM*/, 1*ONE_HOUR,
  4517.          Calendar.OCTOBER,-1, Calendar.SUNDAY /*DOW_IN_DOM*/, 1*ONE_HOUR,
  4518.      1*ONE_HOUR),
  4519.  
  4520.      TimeZone.setDefault( britTime );
  4521.  
  4522.      Or you can then apply that TimeZone to a particular Calendar object
  4523.      like so:
  4524.  
  4525.      Calendar myCal = Calendar.getInstance();
  4526.      myCal.setTimeZone( britTime );
  4527.  
  4528.      If you are running 1.2, You can choose this existing timezone as the
  4529.      default with the code:
  4530.  
  4531.      TimeZone.setDefault( TimeZone.getTimeZone( "Europe/London" ) );
  4532.  
  4533.      Note that BST is defined from JDK 1.1 and later, but it is Bangladesh
  4534.      Standard Time. For a longer example of creating and testing the British
  4535.      timezone, Tony Dahlman provides a nice example in his BSumTime.java
  4536.      code.
  4537.  
  4538.  16. (Sect. 9) How do I create the BST timezone specifically?
  4539.  
  4540.      [*] You can create an arbitrary TimeZone object with the code below. In
  4541.      most or all other timezones, daylight savings time is handled
  4542.      automatically and internally. But GMT is the reference for all other
  4543.      timezones, and so does not have the summertime update applied
  4544.      automatically. The rules for BST can be found at
  4545.      http://www.rog.nmm.ac.uk/leaflets/summer/summer.html
  4546.  
  4547.      Here is the code to create a British Summer Time timezone that is
  4548.      offset one hour from GMT between two dates:
  4549.  
  4550.      import java.util.*;
  4551.      import java.text.*;
  4552.      // create a BST timezone (code courtesy of Tony Dahlman).
  4553.  
  4554.      public static GregorianCalendar setBritSummTime(String zoneName){
  4555.         // Set up the default GMT0BST time zone
  4556.         SimpleTimeZone bst_tz =
  4557.            new SimpleTimeZone( 0,   // no offset from GMT
  4558.                         zoneName,   // individualized tz id
  4559.          // last Sun Mar 1AM
  4560.          Calendar.MARCH,-1,Calendar.SUNDAY,1*60*60*1000,
  4561.          // last Sun Oct 2AM
  4562.          Calendar.OCTOBER,-1,Calendar.SUNDAY,2*60*60*1000
  4563.                         );
  4564.         SimpleTimeZone.setDefault(bst_tz);
  4565.  
  4566.         // Apply TimeZone to create a Calendar object for UK locale
  4567.         return (new GregorianCalendar(bst_tz,Locale.UK) );
  4568.      }
  4569.  
  4570.  
  4571.      and here is how you would print out values using BST:
  4572.  
  4573.      // create a template for printing the date
  4574.      DateFormat df = DateFormat.getTimeInstance(
  4575.                         DateFormat.LONG,Locale.UK);
  4576.  
  4577.      // tell the template to use BST tz.
  4578.      df.setTimeZone(TimeZone.getDefault());
  4579.      System.out.println("Using British Summer Time "
  4580.                        +"the time is: "
  4581.                        + df.format( BritishSummerTime.getTime() ) );
  4582.  
  4583.      // Now get and compare with current time in GMT
  4584.      df.setTimeZone(TimeZone.getTimeZone("GMT") );
  4585.      System.out.println("\nCurrent time in GMT is: "
  4586.                        + df.format(BritishSummerTime.getTime() ) );
  4587.  
  4588.  
  4589.      In the winter, this BST zone is aligned with GMT; in the summer it is
  4590.      one hour later (4 a.m. GMT is 5 a.m. BST).
  4591.  
  4592.      You can look at a list of timezone names and offsets in the file
  4593.      $JAVAHOME/src/java/util/TimeZone.java
  4594.  
  4595.                 java.util.Calendar and java.util.GregorianCalendar
  4596.  
  4597.  17. (Sect. 9)How do I a create a specific date in the Gregorian Calendar?
  4598.  
  4599.      [*]If you have a Date use:
  4600.  
  4601.      myCal.setTime( myDate );
  4602.  
  4603.      If you have a set of integers representing the year, month and day of
  4604.      month use:
  4605.  
  4606.      Calendar myCal = Calendar.getInstance();
  4607.      myCal.set( 1998, Calendar.MARCH, 15 );
  4608.  
  4609.      Note: Months start with January = 0!
  4610.  
  4611.  18. (Sect. 9) How do I use a GregorianCalendar to extract a few fields from
  4612.      a Date?
  4613.  
  4614.      [*]The following code shows how to get some fields from a Date.
  4615.  
  4616.      Calendar g = Calendar.getInstance();
  4617.      g.setTime( aDate );
  4618.      int year = g.get( Calendar.YEAR );
  4619.      int mon = g.get( Calendar.MONTH );
  4620.      int date = g.get( Calendar.DATE );
  4621.      mon++;             // in class Calendar & GregCal, months run 0-11 ;-(
  4622.      System.out.println( mon + "/" + date + "/" + year);
  4623.  
  4624.      If you want to build a string that has a formated date consider using
  4625.      SimpleDateFormat.format().
  4626.  
  4627.  19. (Sect. 9) Some people use Calendar.getInstance() while others use new
  4628.      GregorianCalendar(). Which one is the correct way to get a Calendar?
  4629.  
  4630.      [*] Either way is correct, it depends on what you want to be able to
  4631.      do. You should use Calendar.getInstance(), if you want your code to be
  4632.      ready when the loading of other Calendars are added to the JDK and some
  4633.      other calendar is the default for the locale. A particular locale might
  4634.      have configured a Hebrew or Islamic Calendar as the default calendar
  4635.      and you might want a user to enter a date in his own Calendar, i.e.
  4636.      1-Jan-2000 (Gregorian) = 23-Tevet-576 (Hebrew) = 24-Ramadan-1420
  4637.      (Islamic). If you really are trying to place a particular Gregorian
  4638.      date, i.e. 4-July-1776, into a Date object, you might as well create a
  4639.      GregorianCalendar directly.
  4640.  
  4641.  20. (Sect. 9) I changed a field using Calendar.set() and then I checked
  4642.      another field. Its value is inconsistent with the value I just set.
  4643.      What is going on?
  4644.  
  4645.      [*]In JDK 1.1.0 the Calendar class did not update all of its fields
  4646.      until you called getTime to retrieve the Date that corresponds to the
  4647.      fields in the Calendar. To get the earlier version of the Calendar to
  4648.      "turn the crank" and calculate all fields you can use the trick:
  4649.  
  4650.      myCal.setTime( myCal.getTime() )     // pull the date out and put it back
  4651.      in.
  4652.  
  4653.  21. (Sect. 9) When I create the date July 4th, 1776 using new
  4654.      GregorianCalendar( 1776, 7, 4 ) the month is off by one. What is the
  4655.      problem?
  4656.  
  4657.      [*]You need to be be aware that months start with January equal to 0. A
  4658.      better way to create that date would be:
  4659.  
  4660.      independanceDayUSA = new GregorianCalendar( 1776, Calendar.JULY, 4 );
  4661.  
  4662.  22. (Sect. 9)Why aren't there constants for milliseconds per day, week or
  4663.      year?
  4664.  
  4665.      [*]The short answer is: these values are not constants. While some date
  4666.      calculations would find these useful, it is important to remember that
  4667.      in areas with daylight savings time rules, there are two days per year
  4668.      that are not 24 hours long, therefore not all weeks are the same length
  4669.      (2 out of 52). Also, because of leap years, not all years are the same
  4670.      length.
  4671.  
  4672.      If you adding values to a calendar consider using either add or roll;
  4673.      for example:
  4674.  
  4675.      myCal.add(Calendar.YEAR, 1 );  // get a value 1 year later.
  4676.  
  4677.  23. (Sect. 9) By my count the week of the Year is off by one. What is the
  4678.      problem?
  4679.  
  4680.      [*]The GregorianCalendar class uses the value set by
  4681.      setMinimalDaysInFirstWeek() to determine if the fractional week at the
  4682.      beginning of the year should be week 1 or week 0. If you don't change
  4683.      it, any fractional week could be week 1, depending on the value defined
  4684.      for the locale.
  4685.  24. (Sect. 9) What timezone does a calendar use when I don't explicitly set
  4686.      one?
  4687.  
  4688.      [*]The Calendar uses the TimeZone.getDefault() (see discussion under
  4689.      TimeZone).
  4690.  
  4691.  25. (Sect. 9) Should I stop using Date all together and just use Calendar?
  4692.  
  4693.      [*] Probably not. The Calendar class is a much larger than a Date
  4694.      object. Many other interfaces in standard APIs are defined using a Date
  4695.      object. Use Date objects to hold, store or communicate a date-time
  4696.      value. Use a Calendar object to manipulate a date-time value.
  4697.  
  4698.  26. (Sect. 9) The GregorianCalendar will not accept a date prior to 4713
  4699.      B.C. Why?
  4700.  
  4701.      [*]January 1, 4713 B.C. is the "epoch" date for the Julian Day calendar
  4702.      which was invented in the 16th century by the Joseph Justus Scaliger.
  4703.      "[T]he Julian day calendar, ... does not use individual years at all,
  4704.      but a cycle of 7980 astronomical years that counts a day at a time,
  4705.      with no fractional days, no mean year, and no leap years. He came up
  4706.      with his number by mulitplying three chronological cycles: an 18-year
  4707.      solar cycle, a 19-year lunar cycle, and the 15-year indication period
  4708.      used by Romans. All three cycles began together at the same moment at
  4709.      the start of the "Julian cycle. ... [This] Calendar lives on among
  4710.      astronomers."
  4711.      -- David Ewing Duncan, "Calendar", Avon Books, 1998; p 207
  4712.  
  4713.      Note that the Julian Day calendar is not the same as the Julian
  4714.      calendar. The Julian Calendar is named for Julius Caesar. The Julian
  4715.      Calendar was used in the Europe from what we now call January 1, 45
  4716.      B.C. until at least October 4, 1582 and is still used today by the
  4717.      Eastern Orthodox Church to date holidays.
  4718.  
  4719.      The limitation on dates prior to 4713 BC has been dropped in JDK 1.2.
  4720.  
  4721.  27. (Sect. 9) The Calendar class is said not to handle certain historical
  4722.      changes. Can you explain some of the limitations?
  4723.  
  4724.      [*]The date of change from the Julian to the Gregorian calendar depends
  4725.      on where you lived at the time. The date can vary from 1582 (most
  4726.      Catholic countries, which of course followed the Papal edict) to 1949
  4727.      (China). The date of the cutover from using the Julian Calendar (leap
  4728.      years ever 4 years) to using the Gregorian Calendar (every 4 years,
  4729.      except every 100 unless divisable by 400) is controlled by the method
  4730.      GregorianCalendar.setGregorianChange(Date).
  4731.  
  4732.      It is also the case that January 1 was not always the beginning of the
  4733.      year. January 1 was standardized by Julius Caesar in 45 B.C. and Pope
  4734.      Gregory XIII in 1582, but others who used the Julian Calendar between
  4735.      those dates used other dates for New Years Day. (Anyone who has ever
  4736.      been involved in a standardization effort may find it interesting that
  4737.      neither an emperor nor a pope could actually complete the
  4738.      standardization effort).
  4739.  
  4740.      The Calendar class uses a TimeZone which does not handle historical
  4741.      changes, i.e. the SimpleTimeZone contains only two dates the "spring
  4742.      forward" and "fall back" dates and a date that the DST starts (see
  4743.      SimpleTimeZone.setStartYear() ). If the local definitions have changed
  4744.      then a date/time may not accurately reflect the historical local time.
  4745.  
  4746.      As noted above, the Date object does not usually include leap seconds,
  4747.      unless your hardware includes leap seconds.
  4748.  
  4749.      While the Calendar class is more than useful for international
  4750.      business, it may not be what you want for doing UTC timebased
  4751.      calculations or historical dates and times without a more careful
  4752.      analysis of its design limits.
  4753.  
  4754.                java.text.DateFormat and java.text.SimpleDateFormat
  4755.  
  4756.  28. (Sect. 9) How do I convert a date in one format to another?
  4757.  
  4758.      [*] The following code illustrates the technique:
  4759.  
  4760.      import java.text.*;
  4761.      public class DateTest {
  4762.        public static void main( String[] args ) {
  4763.          SimpleDateFormat df1 =
  4764.            new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
  4765.          SimpleDateFormat df2 =
  4766.            new SimpleDateFormat("dd-MMM-yy");
  4767.          String startdatetime = "1998-09-09 06:51:27.0";
  4768.  
  4769.          try {
  4770.            System.out.println("Date is " +
  4771.              df2.format( df1.parse(startdatetime) ));
  4772.          } catch (ParseException pe) {
  4773.            System.out.println("ParseException " + pe );
  4774.          }
  4775.        }
  4776.      }
  4777.  
  4778.      When run, the program outputs "Date is 09-Sep-98"
  4779.  29. (Sect. 9) How do I use DateFormat to parse a string containing a date?
  4780.  
  4781.      [*] The easiest way to parse a date that is in a known format is to use
  4782.      SimpleDateFormat.parse().
  4783.  
  4784.      DateFormat df = new SimpleDateFormat( "HH:mm" );
  4785.      df.setTimeZone( TimeZone.getDefault() ); // if using JDK 1.1 libraries.
  4786.      df.setLenient( false );                  // to not allow 26:65 etc.
  4787.      Date lateLunchOnDayZero = df.parse( "12:30" );
  4788.      System.out.println( lateLunchOnDayZero );
  4789.  
  4790.      The above code would result in (when in the MST timezone).
  4791.  
  4792.      Thu Jan 01 12:30:00 MST 1970
  4793.  
  4794.      To parse other date and time fields, refer to the SimpleDateFormat
  4795.      documentation.
  4796.  
  4797.  30. (Sect. 9) How do I use a DateFormat to create a text string from a
  4798.      Date?
  4799.  
  4800.      [*] The easiest way to create a string from a date is to use a
  4801.      SimpleDateFormat.format(). The following code illustrates how this can
  4802.      be done.
  4803.  
  4804.      DateFormat df = new SimpleDateFormat( "yyyy.MMM.dd HH:mm:ss.SSS z" );
  4805.      df.setTimeZone( TimeZone.getDefault() ); // JDK 1.1
  4806.      System.out.println( df.format( d ) );    // where d is a Date
  4807.  
  4808.      For other possible fields from the calendar, see the document for
  4809.      SimpleDateFormat.
  4810.  
  4811.  31. (Sect. 9) What timezone does a SimpleDateFormat use when I don't
  4812.      specify one?
  4813.  
  4814.      [*]In JDK 1.1, the SimpleDateFormat uses the first timezone defined for
  4815.      the locale. In JDK 1.2, it uses the default timezone. See the
  4816.      discussion above on how this differs from the Calendar class).
  4817.  
  4818.  32. (Sect. 9) I'm not yet using JDK 1.2 and I don't want the DateFormat to
  4819.      use the 1st timezone for the locale. How do I change the timezone in a
  4820.      SimpleDateFormat to use a different timezone?
  4821.  
  4822.      [*] The following code sets the timezone of a DateFormat to the current
  4823.      default.
  4824.  
  4825.      DateFormat df = DateFormat.getDateInstance();
  4826.      df.setTimeZone(TimeZone.getDefault());
  4827.  
  4828.      or to set it to a timezone of your chioce.
  4829.  
  4830.      df.setTimeZone(TimeZone.getTimeZone( "MST" ) ) // Mtn Time, Denver USA
  4831.  
  4832.  33. (Sect. 9) What century is assumed when I use a two digit year in a
  4833.      SimpleDateFormat string?
  4834.  
  4835.      [*]In JDK 1.1, the default start for the century used by
  4836.      SimpleDateFormat for 2 digit years is 80 years before the current date.
  4837.  
  4838.      This means that in 1998: 1 = 2001, 2 = 2002, ... 17 = 2017, 18 = 2018,
  4839.      19 = 1919, 20 = 1920, ... 98 = 1998, 99 = 1999,
  4840.  
  4841.      In JDK 1.2 you can change this "default century start date" with the
  4842.      method set2DigitYearStart( Date) and get its current value
  4843.      with the method get2DigitYearStart(). One thing to note is that since
  4844.      set2DigitYearStart takes a date not a year, you can have your default
  4845.      century begin at any day or hour.
  4846.  
  4847.      When running under JDK 1.1, it is probably best to avoid two-digit year
  4848.      fields, when the dates entered could possibly fall outside of the range
  4849.      -- now less 80 years and now plus 20 years. If you want to allow
  4850.      two-digit year fields in JDK 1.2 and beyond, consider setting the
  4851.      2DigitYearStart property to something appropriate,  For example, set it
  4852.      to today, when all dates to be entered are in the future (i.e. an
  4853.      expiration date), or set it to today less 100 years, when the value is
  4854.      always in the past (i.e. birthdate, death date).
  4855.  
  4856.  34. (Sect. 9) Does the above mentioned limitation of 2 digit years in JDK
  4857.      1.1 mean that java.text.SimpleDateFormat is not Y2K compliant?
  4858.  
  4859.      [*] No. It means that any code you write that (1) allows the entry of 2
  4860.      digit years and (2) does not make sure they are in an appropriate
  4861.      century, would not pass a careful Y2K analysis. This code was put here
  4862.      so you could sensibly read old files with non-Y2K compliant dates, not
  4863.      so you could create new ones. Once you are using JDK 1.2 it is better
  4864.      to set the 2DigitYearStart property to something appropriate for any
  4865.      two-digit year field which you are parsing.
  4866.  
  4867.                        java.sql.Date and java.sql.TimeStamp
  4868.  
  4869.  35. (Sect. 9) What timezone does a java.sql.date use when converting to an
  4870.      SQL DATE?
  4871.  
  4872.      [*]This is another hidden use of the default java.util.TimeZone. If you
  4873.      have carefully set every timezone in every Calendar and DateFormat you
  4874.      are using, but you don't set the default in java.util.TimeZone when a
  4875.      java.util.Date is converted to a java.sql.Date you may not end up with
  4876.      the value you expected in your database.
  4877.  
  4878.  36. (Sect. 9) When I print a jave.sql.Timestamp it doesn't include any
  4879.      milliseconds. What is the problem?
  4880.  
  4881.      [*] If you print the java.sql.Timestamp directly you will see this
  4882.      problem. The following code demonstrates this surprising behavior.
  4883.  
  4884.      // incorrect use of java.sql.Timestamp
  4885.      DateFormat df = new SimpleDateFormat( "MM/dd/yy hh:mm:ss.SSS a" );
  4886.      df.setTimeZone( TimeZone.getDefault() );    // needed in JDK 1.1
  4887.  
  4888.      java.sql.Timestamp t = new java.sql.Timestamp( 94, Calendar.JANUARY, 1,
  4889.              13, 45, 59, 987654321 );
  4890.      System.out.println( df.format( t ) ) ; // Wrong! no fractions of a second.
  4891.  
  4892.      The results of the above code are:
  4893.  
  4894.      01/01/94 01:45:59.000 PM
  4895.  
  4896.      The above code is using whatever is in the super class (java.util.Date)
  4897.      and assumes all of those parts are filled in. java.sql.Timestamp could
  4898.      have stored the whole milliseconds in the millisecond part of a
  4899.      java.util.Date, and stored the nanoseconds that are not whole
  4900.      milliseconds in an additional field. They chose to ignore the fractions
  4901.      of a second in the java.util.Date and put all fractional parts in an
  4902.      additional nanosecond field.
  4903.  
  4904.      The following code shows how to convert a java.sql.timestamp to a
  4905.      java.util.Date.
  4906.  
  4907.      Date d = new Date(t.getTime() + (t.getNanos() / 1000000 ));
  4908.      // 1 Milli = 1x10^6 Nanos
  4909.      System.out.println( df.format( d ) ) ; // Right! At least we have the millis
  4910.  
  4911.      The result of the above code is a better approximation of the timestamp
  4912.      value:
  4913.  
  4914.      01/01/94 01:45:59.987 PM
  4915.  
  4916.  37. (Sect. 9) How do I calculate the number of days between two dates?
  4917.  
  4918.      [*] There is no API for this (there should be), but you can calculate
  4919.  
  4920.          static final long ONE_HOUR = 60 * 60 * 1000L;
  4921.  
  4922.          Calendar earlierDate = new GregorianCalendar();
  4923.          Calendar laterDate = new GregorianCalendar();
  4924.  
  4925.          earlierDate.set(1997, 1, 5, 0, 0, 0);    // FEB!! 05, 1997
  4926.          laterDate.set(1998, 1, 5, 0, 0, 0);      // Feb 05, 1998
  4927.  
  4928.          // the first getTime() returns a Date, the second takes
  4929.          // that Date object and returns millisecs since 1/1/70.
  4930.          // The API has misleading and horrible naming here, sorry.
  4931.          long duration = laterDate.getTime().getTime() -
  4932.                                    earlierDate.getTime().getTime();
  4933.  
  4934.          // Add one hour in case the duration includes a
  4935.          // 23 hour Daylight Savings spring forward day.
  4936.          long nDays = ( duration + ONE_HOUR ) / (24 * ONE_HOUR);
  4937.          System.out.println("difference in days: " + nDays);
  4938.  
  4939.  
  4940.      Note: this method works only if the two times are both created to be
  4941.      exactly midnight. Otherwise you might end up finding that for example,
  4942.      11 PM tonight is 0 days away from 6 AM tomorrow, instead of 1 day as
  4943.      many applications expect. This is because 24 hours haven't elapsed
  4944.      between 11pm on one day and 6am on the next.
  4945.  
  4946.      Or, use int julian = myCalendar.get(Calendar.DAY_OF_YEAR); and
  4947.      subtract, making sure to subtract the years too. Alternatively, use
  4948.      BigDate at http://mindprod.com.
  4949.  
  4950.      For the ultimate in generality, you could get ACM's Collected Algorithm
  4951.      199, recode it in Java (takes about 30 minutes), compute the Julian
  4952.      date for each end point, and subtract the two numbers. Here is the code
  4953.      in Java to get the GMT Julian day number and a "local Julian Day" that
  4954.      leverages the existing algorithms in the GregorianCalendar.
  4955.  
  4956.      import java.util.*;
  4957.      import java.text.*;
  4958.  
  4959.      /**
  4960.       * This Calendar provides Julian Day and "Calendar Day" methods,
  4961.       * The Calendar Day starts at _local_ midnight.
  4962.       *
  4963.       * @author Paul A. Hill
  4964.       * @version 1.1
  4965.       * @since JDK 1.1.7 3/99
  4966.       * @see java.util.Calendar
  4967.       */
  4968.      public class FAQCalendar extends GregorianCalendar implements Cloneable {
  4969.          /**
  4970.           ** this constant and the ones that follow are actually private
  4971.           ** in the GregorianCalendar, so we'll redefine them here.
  4972.           **/
  4973.          public static final long
  4974.              ONE_SECOND  = 1000,
  4975.              ONE_MINUTE  = ONE_SECOND * 60,
  4976.              ONE_HOUR    = ONE_MINUTE * 60;
  4977.          /**
  4978.           * this next constant and the others with it have their uses,
  4979.           * but watch out for DST days and the weeks that contain them.
  4980.           * Note also that 1/1/1970 doesn't start on the first day of the week.
  4981.           */
  4982.          protected static final long
  4983.              ONE_DAY     = ONE_HOUR * 24,
  4984.              ONE_WEEK    = ONE_DAY  * 7;
  4985.  
  4986.          /** The number of days from Jan 1, 4713 BC (Proleptic Julian)
  4987.           ** to 1/1/1970 AD (Gregorian).  1/1/1970 is time 0 for a java.util.Date.
  4988.           **/
  4989.          public static final long JULIAN_DAY_OFFSET = 2440588L;
  4990.  
  4991.          /**
  4992.           * Same as GregorianCalendar(). Creates a calendar with the time set to
  4993.           * the moment it was created.
  4994.           *
  4995.      Note: for Brevety I have not provided all of the other
  4996.           * constructors that you can find in GregorianCalendar.
  4997.           *
  4998.           * @see java.util.GregorianCalendar#GregorianCalendar
  4999.           */
  5000.          public FAQCalendar() {
  5001.              super();
  5002.          }
  5003.  
  5004.          /**
  5005.           * A calendar day as defined here, is like the Julian Day but it starts
  5006.           * and ends at _local_ 12 midnight, as defined by the timezone which is
  5007.           * attached to this calendar.  This value is useful for comparing
  5008.           * any date in the calendar to any other date to determine how many days
  5009.           * between them, i.e. tomorrow - today = 1
  5010.           *
  5011.           * @return the calendar day (see above).
  5012.           * @see #getCalendarDay
  5013.           */
  5014.          public long getCalendarDay() {
  5015.              TimeZone tz = getTimeZone();
  5016.              // Figure the exact offset for the exact time of day.
  5017.              int offset = tz.getOffset( get( ERA ), get( YEAR ),
  5018.                      get( MONTH ), get( DAY_OF_MONTH ), get( DAY_OF_WEEK ),
  5019.                          (int)((long)get( HOUR_OF_DAY ) * ONE_HOUR +
  5020.                          get( MINUTE ) * ONE_MINUTE +
  5021.                          get( SECOND ) * ONE_SECOND ) );
  5022.              return round( ONE_DAY, getTime().getTime() + offset ) + JULIAN_DAY_OFFSET;
  5023.          }
  5024.  
  5025.          /**
  5026.           * Sets the date in the calendar to 00:00 (midnight) on the local calendar day.
  5027.           * See getCalendarDay for the definition of calendar day as used in this class.
  5028.           *
  5029.           * @param calendarDay the day to set the calendar to.
  5030.           * @see #setCalendarDay
  5031.           * @see java.util.TimeZone#getRawOffset
  5032.           */
  5033.          public void setCalendarDay( long calendarDay ) {
  5034.              // Set to the beginning of the Julian day.
  5035.              // Then add in the difference to make it 00:00 local time.
  5036.              setJulianDay( calendarDay );
  5037.              setTimeInMillis( getTime().getTime() - getTimeZone().getRawOffset() );
  5038.              // we may have gone slightly too far, because we used the
  5039.              // raw offset (diff between Standard time to GMT/UT, instead of the
  5040.              // actual value for this day, so during DLS we may be at 1 AM or whatever
  5041.              // the local DLS offset is), so we'll just drop back to midnight.
  5042.              set( HOUR_OF_DAY, 0 );
  5043.          }
  5044.  
  5045.          /**
  5046.          * Finds the number of days after 12/31/4312 BC 24:00 GMT on a proleptic
  5047.          * Julian Calendar (i.e. extending the Julian Calendar into pre-history)
  5048.          * to the current time.
  5049.          *
  5050.      The Astronomers Julian Day begins at noon.  The Julian Day used here
  5051.          * sometimes called the Chronologists or Historians Julian Day
  5052.          * starts at midnight.  For more information see
  5053.          * http://www.magnet.ch/serendipity/hermetic/cal_stud/jdn.htm#astronomical
  5054.          *
  5055.      Note: This routine does NOT take into consideration
  5056.          * leap seconds.
  5057.          *
  5058.          * @return the day number of the current time from 1/
  5059.          * @see #getCalendarDay
  5060.          */
  5061.          public long getJulianDay() {
  5062.              return round( ONE_DAY, getTime().getTime() ) + JULIAN_DAY_OFFSET;
  5063.          }
  5064.  
  5065.          /**
  5066.          * Sets the current date contained in this calendar to exactly
  5067.          * 00:00 GMT on the date defined by the Julian Day provided.
  5068.          *
  5069.          * @param julianDay the Julian Day to set the calendar to
  5070.          * @see #setCalendarDay
  5071.          */
  5072.  
  5073.          public void setJulianDay( long julianDay ) {
  5074.              setTimeInMillis( ( julianDay - JULIAN_DAY_OFFSET ) * ONE_DAY );
  5075.          }
  5076.  
  5077.          /**
  5078.           * This is a utility routine for rounding (toward negative) to the nearest
  5079.           * multiple of the conversion factor.
  5080.           *
  5081.      BUG? Why is this different than the formula given in
  5082.           * java.util.GregorianCalendar private millisToJulianDay?
  5083.           *
  5084.           * @param conversion typically one of the constants defined
  5085.           * above ONE_MINUTE, ONE_DAY etc.
  5086.           * @param fractions the value to convert expressed in the same units
  5087.           * as the conversion factor (i.e milliseconds).
  5088.           *
  5089.           * @return the value divided by the conversion factor, rounded to the negative.
  5090.           * @see java.util.Calendar
  5091.           */
  5092.          protected static final long round( long conversion, long fractions ) {
  5093.              long wholeUnits;
  5094.  
  5095.              // round toward negative:
  5096.              // For secs rounded to minutes -61/60=-1, -60/60=-1, -59/60=0,
  5097.              //      but we want -2, -1, -1 not -1,-1,0
  5098.              // or month 0..11 => year 1; -12..-1 => 0; -24..-13 => -1
  5099.  
  5100.              if ( fractions >= 0 ) {
  5101.                  wholeUnits = fractions / conversion;
  5102.              }
  5103.              else {
  5104.                  wholeUnits = ( fractions + 1 )/ conversion - 1;
  5105.              }
  5106.              return wholeUnits;
  5107.          }
  5108.      } // FAQCalendar
  5109.  
  5110.  
  5111.                        -------------------------------
  5112.  
  5113. 10. AWT
  5114.  
  5115.                           Text, Textfield, and TextArea
  5116.  
  5117.   1. (Sect. 10) How can I write text at an angle?
  5118.  
  5119.      [*] Check out http://www.nyx.net/~jbuzbee/font.html. Jim has some code
  5120.      to do exactly this. A good way to do it is to draw the text to an
  5121.      offscreen image and write an ImageFilter to rotate the image.
  5122.  
  5123.      Also, from JDK 1.2 on, the Java 2D API handles arbitrary shapes, text,
  5124.      and images and allows all of these to be rotated, scaled, skewed, and
  5125.      otherwise transformed in a uniform manner. A code example would be:
  5126.  
  5127.      import java.awt.*;
  5128.      import java.awt.geom.*;
  5129.      public class r extends Frame {
  5130.  
  5131.          public static void main(String args[]) { new r(); }
  5132.  
  5133.          r() { setSize(200,200); setVisible(true); }
  5134.  
  5135.          public void paint(Graphics g) {
  5136.              Graphics2D g2D = (Graphics2D) g;
  5137.              AffineTransform aft = new AffineTransform();
  5138.              aft.setToTranslation(100.0, 100.0);
  5139.              g2D.transform(aft);
  5140.              aft.setToRotation(Math.PI / 8.0);
  5141.              String s = "Rotated Hello World";
  5142.  
  5143.              for (int i = 0; i < 16; i++) {
  5144.                  g2D.drawString(s, 0.0f, 0.0f);
  5145.                  g2D.transform(aft);
  5146.              }
  5147.          }
  5148.      }
  5149.  
  5150.      There is more info about the 2D API at
  5151.      http://java.sun.com/products/java-media/2D/index.html and
  5152.      http://developer.javasoft.com/developer/technicalArticles/
  5153.  
  5154.   2. (Sect. 10) How do you change the font type and size of text in a
  5155.      TextArea?
  5156.  
  5157.      [*] Like this.
  5158.  
  5159.      myTextArea.setFont(new Font("NAME", <STYLE>, <SIZE>));
  5160.  
  5161.      where:
  5162.         o NAMEis the name of the font (e.g. Dialog or TimesRoman).
  5163.         o <STYLE> is Font.PLAIN, Font.ITALIC, Font.BOLD or any additive
  5164.           combination (e.g. Font.ITALIC+Font.BOLD).
  5165.         o <SIZE> is the size of the font, e.g. 12.
  5166.  
  5167.      Example: new Font("TimesRoman", Font.PLAIN, 18);
  5168.  
  5169.   3. (Sect. 10) Can you have different fonts for individual words in a
  5170.      TextArea?
  5171.  
  5172.      [*] No. If you're trying to write a word processor, use the Canvas
  5173.      class to render on. Note that this can be done using the Swing JText
  5174.      classes.
  5175.  
  5176.   4. (Sect. 10) How much text can be put in a TextArea?
  5177.  
  5178.      [*] TextArea just uses the corresponding widget of the underlying
  5179.      window system. It will be bounded by the limit imposed in the native
  5180.      window system. In Windows 95 TextAreas can hold about 28Kb. The native
  5181.      widget allows 32Kb, but there is some overhead which reduces the amount
  5182.      available to the programmer. The limit is removed in JTextComponent in
  5183.      Swing (JDK 1.2) which dispenses with peer controls.
  5184.  
  5185.   5. (Sect. 10) How do I clear the contents of a TextArea?
  5186.  
  5187.      [*] Set it to an empty String with this:
  5188.  
  5189.      area.setText("");
  5190.  
  5191.   6. How do I get back to a normal echo after I have used
  5192.      TextField.setEchoChar('*')?
  5193.  
  5194.      [*] TextField.setEchoChar('\0') works on most Windows-based
  5195.      browsers...but for most other platforms (i.e. Netscape under UNIX), it
  5196.      just locks up the textfield.
  5197.  
  5198.      There is only one good solution, and that is to make two TextFields on
  5199.      top of each other, one normal, and one with .setEchoChar('*'), and
  5200.      switch between them.
  5201.  
  5202.   7. (Sect. 10) How do I get word wrap in a TextArea?
  5203.  
  5204.      [*] It's a little obscure. Creating a TextArea with no horizontal
  5205.      scrollbar causes wrapping to occur automatically. The idea is that if
  5206.      you ask for a scroll to scroll viewing over to the right, there is no
  5207.      reason for the widget to do word wrap. So take away the scrollbar, and
  5208.      word wrap will be done instead.
  5209.  
  5210.      Supply TextArea.SCROLLBARS_NONE or TextArea.SCROLLBARS_VERTICAL_ONLY to
  5211.      the TextArea constructor to get word wrap. By default, a TextArea is
  5212.      created with both horizontal and vertical scrollbars.
  5213.  
  5214.   8. (Sect. 10) How can I limit a TextField to no more than N characters, or
  5215.      to only allow numeric input?
  5216.  
  5217.      [*] The approach is to look at keystrokes as they happen, and disallow
  5218.      input that does not meet your criteria.
  5219.  
  5220.      A neat variation is to extend the basic AWT component, and in your
  5221.      subclass also include the handler that will look at the keystrokes.
  5222.      This bundles everything neatly in one place. The code may look like:
  5223.  
  5224.      import java.awt.*;
  5225.      import java.awt.event.*;
  5226.  
  5227.      public class XCTextField extends java.awt.TextField implements
  5228.      java.awt.event.TextListener {
  5229.  
  5230.          public XCTextField(int columns) {
  5231.              super(columns);
  5232.              enableEvents(AWTEvent.FOCUS_EVENT_MASK);
  5233.              addTextListener(this);
  5234.          }
  5235.  
  5236.          // other constructors may be useful, too
  5237.  
  5238.          public void textValueChanged(java.awt.event.TextEvent event) {
  5239.              int col = this.getColumns();
  5240.              int len = getText().length();
  5241.           // int caret = getCaretPosition();
  5242.  
  5243.              if (col > 0 && len  > col) {
  5244.              // or if the char just entered is not numeric etc.
  5245.                      String s = this.getText();
  5246.                      Toolkit.getDefaultToolkit().beep();
  5247.                      this.setText(s.substring(0,col));
  5248.                      this.setCaretPosition(col-1);  // caret at end
  5249.              }
  5250.  
  5251.          }
  5252.  
  5253.          public void processFocusEvent(java.awt.event.FocusEvent e) {
  5254.          // this routine highlights according to focus gain/loss.
  5255.              super.processFocusEvent(e);
  5256.              int id = e.getID();
  5257.              if (id==java.awt.event.FocusEvent.FOCUS_GAINED)
  5258.                  this.selectAll();
  5259.              else if (id==java.awt.event.FocusEvent.FOCUS_LOST)
  5260.                  this.select(0,0);
  5261.          }
  5262.      }
  5263.  
  5264.      Here is a much briefer example, which very cleverly does the work in
  5265.      the Listener. Oracle really dislikes the "apostrophe" character in a
  5266.      data text fields, as it is interpreted as part of an SQL statement.
  5267.      Here is the code that James Cloughley wrote to suppress apostrophes
  5268.      ("ticks") in a TextField.
  5269.  
  5270.      import java.awt.*;
  5271.      import java.awt.event.*;
  5272.      public class NoTick extends KeyAdapter {
  5273.          final char tick = '\'';
  5274.  
  5275.          public void keyPressed( KeyEvent event ) {
  5276.              TextComponent tc = ( TextComponent )event.getSource();
  5277.              char c = event.getKeyChar();
  5278.              if ( c == tick ) { event.consume(); }
  5279.          }
  5280.      }
  5281.  
  5282.      Use it like this:
  5283.  
  5284.      TextField sometextfield = new TextField();
  5285.      sometextfield.addKeyListener( new NoTick() );
  5286.  
  5287.  
  5288.      Brief and clever - make the event handler consume unwanted characters.
  5289.      However, it doesn't filter out text that arrives in the component via
  5290.      cut & paste! If you use ctrl-v to paste, you get key events for the
  5291.      ctrl and v, but not for the characters that are pasted.
  5292.  
  5293.      Finally, check out iDate, iTime, and iNumeric from IBM's alphaworks
  5294.      javabeans, available free at http://www.alphaworks.ibm.com/alphaBeans.
  5295.      These beans do the kind of validation you want.
  5296.  
  5297.                                 Size and Position
  5298.  
  5299.   9. (Sect. 10) I use add(Component) to add Components to the Container. Is
  5300.      there any way to explicitly set the z-order of these Components?
  5301.  
  5302.      [*] JDK 1.0 has no way to explicitly set the z-order of components. You
  5303.      can try it heuristically, based on the browser you're using, or you can
  5304.      use CardLayoutManager to ensure the panel you want is at the front.
  5305.  
  5306.      In JDK 1.1, the z-order of components ("z-order" means "front-to-back"
  5307.      order, i.e. which window is in front of which) can be controlled by
  5308.      using the the method add(Component comp, int index). By default,
  5309.      components are added 0 to N. The method paint of class Container paints
  5310.      its visible components from N to 0.
  5311.  
  5312.  10. (Sect. 10) How can I get the dimensions and resolution of the screen?
  5313.  
  5314.      [*] Use
  5315.  
  5316.      java.awt.Toolkit.getDefaultToolkit().getScreenSize()
  5317.  
  5318.      or
  5319.  
  5320.      java.awt.Toolkit.getDefaultToolkit().getScreenResolution()
  5321.  
  5322.      Screen resolution is in dots-per-inch.
  5323.  
  5324.      Take a look in the Toolkit class for other useful methods.
  5325.  
  5326.      Toolkit.getDefaultToolkit().getColorModel().getPixelSize()
  5327.  
  5328.      gets you the color model in terms of bits per pixel.
  5329.  
  5330.      Math.pow(2, Toolkit.getDefaultToolkit().
  5331.          getColorModel().getPixelSize())
  5332.  
  5333.      gets you the color model in terms of number of colors. Or use this:
  5334.  
  5335.      1 << Toolkit.getDefaultToolkit().
  5336.          getColorModel().getPixelSize()
  5337.  
  5338.      That does a shift left to calculate the power of two.
  5339.  
  5340.  11. (Sect. 10) How do I allow for the size of the title bar and border when
  5341.      I draw a Frame?
  5342.  
  5343.      [*] Use MyFrame.getInsets(). This returns a java.awt.Insets object
  5344.      which has four ints: top, left, bottom, right, giving the number of
  5345.      pixels each of those margins are inset from the top. You can use these
  5346.      value to adjust the Dimension object returned by component.getSize().
  5347.  
  5348.      If you are doing this in the constructor you need to ensure that the
  5349.      Frame's peer object is created first. Otherwise the Insets object
  5350.      returned by getInsets() will have all zero values. Make a call to
  5351.      Frame.addNotify() to have the peer created.
  5352.  
  5353.  12. (Sect. 10) How do I resize a List? I had a List defined as
  5354.  
  5355.      List tlist = new List(10);
  5356.  
  5357.      but the Strings in the list were 80 characters long and only the first
  5358.      15 were being shown. I was not able to resize the List to display the
  5359.      contents without using the scroll bar.
  5360.  
  5361.      [*] A List cannot be resized in a constructor, so add the following to
  5362.      the Applet (or wherever):
  5363.  
  5364.      public void paint (Graphics g) {
  5365.          tlist.setSize(200,200);
  5366.      }
  5367.  
  5368.      Then before showing panel/frame with the List:
  5369.  
  5370.      tlist.resize(400,400);
  5371.  
  5372.  13. (Sect. 10) How can my program tell when a window is resized?
  5373.  
  5374.      [*] Override the setBounds(int,int,int,int) method of Component to do
  5375.      what you want. Of course, have it call super.setBounds() as well. Note
  5376.      that setBounds() replaces reshape() which is deprecated.
  5377.  
  5378.      Note the new APIs call the deprecated APIs instead of the other way
  5379.      round. For example, Component.setBounds calls Component.reshape,
  5380.      instead of reshape calling setBounds. This is because the AWT sometimes
  5381.      needs to call these for its own purposes. If it called the old one
  5382.      which then called the new one, and you overrode the new one, the AWT
  5383.      would (wrongly) not call your routine. By having the AWT call the new
  5384.      one (and then the new one call the old one), any overrides of the new
  5385.      one will correctly be called by the AWT as needed. If that didn't make
  5386.      sense, forget I mentioned it.
  5387.  
  5388.  14. (Sect. 10) How do I center a dialog box?
  5389.  
  5390.      [*] You cannot currently get the applet's absolute screen coordinates.
  5391.      Its location (0,0) is relative to the browser, not the screen itself.
  5392.      But you can center something that it pops up or displays centered on
  5393.      the screen with code like this:
  5394.  
  5395.      Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
  5396.      my_window.move(
  5397.       ( screen.width - my_window.size().width ) / 2,
  5398.       ( screen.height - my_window.size().height ) / 2 );
  5399.  
  5400.      my_window.show().
  5401.  
  5402.      In a related fashion, you can center something on its parent like this.
  5403.      Note the intelligent use of APIs like translate() to do the work for
  5404.      you.
  5405.  
  5406.      void center(Component parent) {
  5407.          pack();
  5408.  
  5409.          Point p = parent.getLocation();
  5410.          Dimension d = parent.getSize();
  5411.          Dimension s = getSize();
  5412.  
  5413.          p.translate((d.width - s.width) / 2,
  5414.                      (d.height - s.height) / 2);
  5415.          setLocation(p);
  5416.      }
  5417.  
  5418.  15. (Sect. 10) How can I get the absolute mouse coordinates?
  5419.  
  5420.      [*] You mean, if the browser is about 640x480, you want a y-coord
  5421.      between 0 and 480. If the browser window is about 800x600 you want a
  5422.      y-coord between 0 and 600. This might be needed for a pop-up menu,
  5423.      where you want to pop up at the absolute mouse position.
  5424.  
  5425.      The approach is to sum up the event's (x,y) and the locations of the
  5426.      target and its parents until there is no parent. Though on some
  5427.      browsers, it seems this is not reliable. [Better suggestions are
  5428.      solicited.]
  5429.  
  5430.  16. (Sect. 10) How do I detect a resize of a Frame or other Component?
  5431.  
  5432.      [*] If you are using JDK 1.0.2, you can override the reshape(int, int,
  5433.      int, int) method of Component to do what you want; of course, have it
  5434.      call super.reshape() as well.
  5435.      In JDK 1.1.x, setBounds() replaces reshape(), which is deprecated -
  5436.      however, there is a better way of detecting the resize using the new
  5437.      event model, than overriding setBounds(). Note the new APIs call the
  5438.      depecated one.
  5439.  
  5440.      The proper way to detect the resize in 1.1.x is to register a
  5441.      ComponentListener on the Frame, like this:
  5442.  
  5443.      import java.awt.*;
  5444.      import java.awt.event.*;
  5445.  
  5446.      class MyFrame extends Frame {
  5447.          public MyFrame() {
  5448.              addComponentListener(new CmpAdapter());
  5449.          }
  5450.  
  5451.          class CmpAdapter extends ComponentAdapter {
  5452.              public void componentResized(ComponentEvent evt) {
  5453.                  //doSomething();
  5454.              }
  5455.          }
  5456.      }
  5457.  
  5458.      Alternatively, the same effect can be achieved like this:
  5459.  
  5460.      class MyFrame extends Frame implements ComponentListener {
  5461.          public MyFrame() {
  5462.              addComponentListener(this);
  5463.          }
  5464.  
  5465.          public componentHidden(ComponentEvent evt) { }
  5466.          public componentMoved(ComponentEvent evt) { }
  5467.          public componentShown(ComponentEvent evt) { }
  5468.          public componentResized(ComponentEvent evt) {
  5469.              //doSomething
  5470.          }
  5471.      }
  5472.  
  5473.      Or even with an anonymous inner class
  5474.  
  5475.        public MyFrame() {
  5476.                addComponentListener(new ComponentAdapter() {
  5477.                  public void componentResized(ComponentEvent evt) {
  5478.                    // doSomething;
  5479.              }
  5480.            } );
  5481.          }
  5482.  
  5483.  17. (Sect. 10) What are those preferredSize() and minimumSize() methods in
  5484.      Component?
  5485.  
  5486.      [*] Those methods allow a LayoutManager to calculate the preferred and
  5487.      minimum sizes of the Components it is arranging. You can control the
  5488.      values that the LayoutManager gets by creating subclasses of the
  5489.      Components you are using and overriding these methods. You don't call
  5490.      them; you override them and they are called on your behalf.
  5491.  
  5492.  18. (Sect. 10) Why isn't my component showing up at all? Or in some cases
  5493.      not until I resize the main window?
  5494.  
  5495.      [*] The initial sizes of components are not always exactly what the
  5496.      programmer would expect. When a component doesn't show up, often it is
  5497.      getting added to its parent, but with a size of 0x0. Even when
  5498.      getPreferredSize gives a non-zero value. If this seems to be what's
  5499.      happening, try calling setSize(getPreferredSize()). If that doesn't
  5500.      seem to be the problem, look into your layout manager.
  5501.  
  5502.                                 Drawing and Pixels
  5503.  
  5504.  19. (Sect. 10) How do I plot a single pixel to the screen?
  5505.  
  5506.      [*] Use g.drawLine(x1,y1,x1,y1) to draw a line one pixel in length. If
  5507.      you are drawing a very large number of individual pixels, consider
  5508.      using a java.awt.MemoryImageSource object and measure whether this
  5509.      offers better performance.
  5510.  
  5511.  20. (Sect. 10) Is it possible to draw a polygon or a line more than 1 pixel
  5512.      wide?
  5513.  
  5514.      [*] JDK 1.1 doesn't have support for this. The standard workaround for
  5515.      drawing a thick line is to draw a filled polygon. The standard
  5516.      workaround for drawing a thick polygon is to draw several polygons.
  5517.  
  5518.      There is a useful class at
  5519.      http://www.apl.jhu.edu/~hall/java/GraphicsUtil.html which extends the
  5520.      drawxxx and fillxxx methods of java.awt.Graphics. It adds a Line Width
  5521.      argument to most of the drawxxx methods, a Color argument to most of
  5522.      the drawxxx and fillxxx methods, and a Font argument to drawString and
  5523.      drawChars.
  5524.  
  5525.      JDK 1.2 introduces the java.awt.BasicStroke class. You set the stroke
  5526.      on a Graphics object, and line rendering is done using that info.
  5527.  
  5528.              BasicStroke bs = new BasicStroke(width, BasicStroke.CAP_BUTT,
  5529.                                       BasicStroke.JOIN_MITER, 1.0f, null, 0.0f);
  5530.              g.setStroke(bs);
  5531.              g.drawLine( ... );
  5532.  
  5533.  21. (Sect. 10) How can I make an offscreen image with transparent pixels?
  5534.      How can I grab the pixel values from an offscreen image?
  5535.      How can I use AWT drawing primitives (e.g. drawString() or drawOval())
  5536.      on an image I created from an ImageProducer?
  5537.  
  5538.      [*] None of these things can be done.
  5539.  
  5540.      Despite the fact that there is only one class called Image in the AWT
  5541.      libraries, it suffers from a (currently undocumented) severe case of
  5542.      schizophrenia: The code behaves as though there are two unrelated types
  5543.      of Image. The first type are those created by the
  5544.      Component.createImage(int, int) call, known as "offscreen" images, and
  5545.      the second are those created by the
  5546.      Component.createImage(ImageProducer) call, or by the
  5547.      Toolkit/Applet.getImage() calls, which I will call "produced" images.
  5548.  
  5549.      The only common ground between these kinds of Image is the following:
  5550.         o You may find their width and height by the methods of the Image
  5551.           class.
  5552.         o You may use them as the argument to the various
  5553.           Graphics.drawImage() calls.
  5554.      The differences between these objects are the following:
  5555.         o You may not put transparent pixels into an offscreen - note that
  5556.           all Java primitives accept Color objects, which all represent
  5557.           completely opaque colours as if Produced from an int with the
  5558.           upper 8 bits equal to 0xff. (See also Question 8.3.)
  5559.         o You may not call Image.getGraphics() on a produced image, and
  5560.           hence may not use any AWT primitives.
  5561.         o You may not grab pixels from an offscreen image using
  5562.           PixelGrabber.
  5563.         o Anyone know of any other limitations?
  5564.      In these cases, "you may not" generally means "you may not
  5565.      successfully". Symptoms on attempting these range from Exceptions to
  5566.      garblings of the Image. Any or all of these restrictions may be removed
  5567.      in Java 1.2, which features a new 2D API. Wait and see.
  5568.      Workaround: cause a peer to be created for the Image, and then do the
  5569.      operation. It will work. You can add it to a Frame, for example. You do
  5570.      not have to show() the Frame. Causing the peer to be created is enough.
  5571.  
  5572.      There are some relevant bugs shown in the Java Developer Connection:
  5573.      Bug ID 4098505. Apparently, from the report from the Sun engineer,
  5574.      PixelGrabber is specified to work with offscreen images, just it is
  5575.      currently buggy, and invariably gets the wrong color model. No fix has
  5576.      been scheduled yet.
  5577.  
  5578.      Bug ID 4077718 reports that setting transparent Colors in offscreen
  5579.      images has been available since Java 1.2b1. I am personally unable to
  5580.      verify this.
  5581.  
  5582.      There is an incorrect answer from Sun to the third matter, of
  5583.      getGraphics() on produced images, in article 1501 in Questions&Answers.
  5584.  
  5585.  22. (Sect. 10) How can I grab a pixel from an Image object?
  5586.  
  5587.      [*] This is the purpose of the java.awt.image.PixelGrabber class. A
  5588.      fragment of code showing its use is:
  5589.  
  5590.      import java.awt.image.PixelGrabber;
  5591.      import java.awt.Image;
  5592.         ...
  5593.      public static int pixelValue(Image image, int x, int y) {
  5594.      // precondition: buffer must not be created from ImageProducer!
  5595.      // x,y should be inside the image,
  5596.      // Returns an integer representing color value of the x,y pixel.
  5597.          int[] pixel=new int[1];
  5598.          pixel[0]=0;
  5599.  
  5600.      // pixel grabber fills the array with zeros if image you are
  5601.      // trying to grab from is non existent (or throws an exception)
  5602.          PixelGrabber grabber = new PixelGrabber(image,
  5603.                                           x, y, 1, 1, pixel, 0, 0);
  5604.          try {
  5605.              grabber.grabPixels();
  5606.          } catch (Exception e) {System.err.println(e.getMessage());}
  5607.          return pixel[0];
  5608.      }
  5609.  
  5610.      By the way, one issue on working with images is that the Java VM will
  5611.      consume virtual memory pretty fast if you are loading lots of images
  5612.      without calling the Image.flush() method when done. The getImage()
  5613.      method probably caches old images so they aren't garbage collected.
  5614.  
  5615.                                   Other AWT FAQs
  5616.  
  5617.  23. (Sect. 10) How do I change the icon on my Frame or JFrame from the Java
  5618.      coffee cup to my own icon?
  5619.  
  5620.      [*] Just use
  5621.  
  5622.      f.setIconImage( Toolkit.getDefaultToolkit().getImage(iconfilename) );
  5623.  
  5624.      On Windows, the icon must be 16-by-16 pixels.
  5625.  
  5626.  24. (Sect. 10) What's all this about subclassing Canvas and overriding
  5627.      paint() ? Can't I just do a getGraphics() for a component, and draw
  5628.      directly on that?
  5629.  
  5630.      [*] You can do that, and it might work up to a point (or it might not).
  5631.      A problem arises when the window system wants to refresh that component
  5632.      e.g. because it has been partially obscured and is now revealed. It
  5633.      calls paint(), and paint() has no knowledge of the other g.drawing()
  5634.      you have just done.
  5635.  
  5636.  25. (Sect. 10) But couldn't the AWT just remember what has been drawn to a
  5637.      Graphics context, and replicate that instead of calling paint()?
  5638.  
  5639.      [*] Possibly it could, but how do you unremember something that has
  5640.      been drawn? How do you start drawing over again with different
  5641.      contents? You could solve these by creating extra methods, but that is
  5642.      not how it works. In practice it is a lot simpler to be able to look at
  5643.      the paint method, and see explicitly all the things that will be done
  5644.      to draw that component. Bottom line: Use paint(), not g=getGraphics();
  5645.      g.drawString( ...
  5646.  
  5647.  26. (Sect. 10) When I call repaint() repeatedly, half my requests get lost
  5648.      and don't appear on the screen. Why is this?
  5649.  
  5650.      [*] repaint() just tells the AWT that you'd like a paint to happen. AWT
  5651.      will fold several adjacent repaint requests into one, so that only the
  5652.      most current paint is done. One possible workaround might be to use a
  5653.      clip rectangle and only paint the different areas that have changed.
  5654.  
  5655.  27. (Sect. 10) Why do I get this when using JDK 1.1 under X Windows?
  5656.  
  5657.      java.lang.NullPointerException
  5658.      at sun.awt.motif.MFramePeer.<init>(MFramePeer.java:59)
  5659.      at sun.awt.motif.MToolkit.createFrame(MToolkit.java:153)
  5660.      at java.awt.Frame.addNotify(Frame.java)
  5661.      at java.awt.Window.pack(Window.java)
  5662.  
  5663.      [*] There's a missing font on your system. Move font.properties from
  5664.      the "lib" subdirectory aside to font.properties.bak. Then it won't look
  5665.      for the font and fail to find it.
  5666.  
  5667.      The problem occurs because the Motif AWT libraries use the Font "plain
  5668.      Dialog 12 point" as a fall-back default font. Unfortunately, when using
  5669.      a remote X server sometimes this font isn't available.
  5670.  
  5671.      On an X terminal, the diagnostic may be slightly different, a segv
  5672.  
  5673.      % appletviewer HelloWorldApplet.html
  5674.      SIGSEGV 11* segmentation violation
  5675.      si_signo [11]: SIGSEGV 11* segmentation violation
  5676.      si_errno [0]: Error 0
  5677.      si_code [1]: SEGV_ACCERR [addr: 0x14]
  5678.  
  5679.      To determine which fonts you have, issue a command such as
  5680.  
  5681.      xlsfonts > ~/fonts.txt
  5682.  
  5683.      Then pick through the long list of fonts to determine which ones you
  5684.      want to use. The xfd program will let you look at a font:
  5685.  
  5686.      xfd -fn "your font name here" &
  5687.  
  5688.  28. (Sect. 10) Why is GridBagLayout so hard to use?
  5689.  
  5690.      [*] There are two reasons. First, while simple layouts are easy.
  5691.      detailed GUI layout is difficult. Second, GridBagLayout wasn't designed
  5692.      with human factors and ease of use in mind. If that bothers you (it
  5693.      bothers me) then don't use it. Create your GUI on several panels and
  5694.      use the other layout managers as appropriate to get the exact effect
  5695.      you want. The official story from the project leader of the AWT
  5696.      project, as explained to the Mountain View Java Users Group on December
  5697.      4 1996, is:
  5698.           "The case has been made and is now accepted that GridBagLayout is
  5699.           too hard to use for what it offers. GBL will continue to be
  5700.           supported, and something better and simpler will eventually be
  5701.           provided as well. This 'better GBL' can be used instead of GBL."
  5702.      Bottom line: nobody has to spend any effort on GBL, there are simpler
  5703.      alternatives available now. In addition GBL is the source of a memory
  5704.      leak. GBL puts "added" components into a hashtable, but
  5705.      removeLayoutComponent() never removes them. See bug 4195295.
  5706.  
  5707.      GBL documentation is hard to come by. Based on the obvious similarity,
  5708.      it could have been derived from the Tk (of Tcl/Tk) grid layout manager.
  5709.      If you're not a fan of nesting panels, and none of the other layout
  5710.      managers do what you want (or you're working with legacy code that
  5711.      already uses it), you might find some Tk documentation worth a look.
  5712.  
  5713.  29. (Sect. 10) MyClass works fine except when I try to set a particular
  5714.      font. I just can't seem to get it to work in Win95, but I can get it to
  5715.      work on a MacOS and Unix.
  5716.  
  5717.      [*] You probably specified a font name that isn't available under your
  5718.      Win95 installation; this is one of those cross-platform differences
  5719.      that can bite you if you over-specify for one platform, like specifying
  5720.      "Arial" as a font and expecting it to work on something other than
  5721.      Windows.
  5722.  
  5723.      On both Windows 95 and Solaris 2.6, these fonts
  5724.         o Dialog
  5725.         o SansSerif
  5726.         o Serif
  5727.         o Monospaced
  5728.         o Helvetica
  5729.         o TimesRoman
  5730.         o Courier
  5731.         o DialogInput
  5732.         o ZapfDingbats
  5733.      are revealed by this code:
  5734.  
  5735.      import java.awt.*;
  5736.  
  5737.      class foonly {
  5738.          static public void main(String s[])
  5739.          {
  5740.              String n[]= new Frame().getToolkit().getFontList();
  5741.              for (int i=0;i<n.length; i++)
  5742.                  System.out.println(n[i]);
  5743.  
  5744.              System.exit(0);
  5745.          }
  5746.      }
  5747.  
  5748.      In other words, You can get a String array of the names of the fonts by
  5749.  
  5750.      String[] fonts = Toolkit.getDefaultToolkit().getFontList()
  5751.  
  5752.      The names of actual fonts like Helvetica, TimesRoman, and Courier are
  5753.      deprecated in JDK 1.1 in favor of font styles like SansSerif, Serif,
  5754.      and Monospaced (respectively). The font style will be mapped into the
  5755.      nearest actual font on a platform.
  5756.  
  5757.      The font styles are now mapped into a system font name using the
  5758.      entries in one of the font.properties files in $JAVAHOME/lib. There are
  5759.      multiple font.properties files corresponding to different locales. If
  5760.      you wanted a quick hack for testing, you could modify the file or add
  5761.      to it so a different mapping is done to a new font you want to try.
  5762.  
  5763.  30. (Sect. 10) I've made a Lightweight Component (a Component directly
  5764.      extending Component), and it keeps flickering/doesn't repaint itself
  5765.      properly. Why is this?
  5766.  
  5767.      [*] Lightweight Components, since they are notionally meant to be
  5768.      "transparent", aren't painted directly in response to repaint(), but in
  5769.      fact, Component.repaint() goes up the stack of Components until it
  5770.      finds an "Opaque" Heavyweight Component (necessarily a Container), and
  5771.      then calls repaint() on *that*.
  5772.  
  5773.      At this point, a call is eventually scheduled to Container.update().
  5774.      His first action is to call super.update, plunging us into
  5775.      Component.update(), which clears the component to the background color,
  5776.      since it has been called on a heavyweight, and returns. Then
  5777.      Container.update() proceeds merrily to call update on all contained
  5778.      Lightweight Components, recursively.
  5779.  
  5780.      The bottom line: "transparency" of lightweight components will only
  5781.      work correctly (without flickering) if the first upwardly accessible
  5782.      heavyweight component in the containment hierarchy is
  5783.         o a double-buffered heavyweight Component (necessarily a Container),
  5784.           or
  5785.         o a heavyweight that never updates, but always paints (i.e. one that
  5786.           has overriden the default update() mechanism to not clear the
  5787.           background).
  5788.      If this is not done, the default Component update() will always clear
  5789.      the background before any repainting is done, leading to annoying
  5790.      flickering.
  5791.  
  5792.      Another important point is that if your Container has its own paint()
  5793.      method, that paint method of the container must call
  5794.      super.update/paint(), otherwise the contained lightweight components
  5795.      will never be painted. Putting this all together, the minimal
  5796.      alteration to code to cause it to work in this case is to place the
  5797.      method
  5798.  
  5799.      public void update(Graphics g) {
  5800.          super.paint(g);
  5801.      }
  5802.  
  5803.      in the most closely containing heavyweight Container, in a Component
  5804.      hierarchy where you want to smoothly render lightweights that do not
  5805.      paint areas extending past that painted by their parents, i.e. ones
  5806.      that are not "transparent". This is dirty, but quick.
  5807.  
  5808.      If you want smooth transparency, the call above should read
  5809.  
  5810.  
  5811.        public void update(Graphics g) {
  5812.          // standard offscreen generation here.
  5813.          offg.fillRect(required background colour, full size);
  5814.          super.paint(offg);
  5815.          g.drawImage(myimage, 0, 0, null);
  5816.          }
  5817.  
  5818.        public void paint(Graphics g) {
  5819.          // can generally expect resizes will hit update() first.
  5820.          super.paint(offg);
  5821.          g.drawImage(myimage, 0, 0, null);
  5822.          }
  5823.  
  5824.      It's possible to intertwine these, by having this.update() calling
  5825.      this.paint(), with various replacings of the argument, but it is
  5826.      clearest to override them separately, as in the example.
  5827.  
  5828.  31. (Sect. 10) What is the difference between Component's
  5829.      setForeground(Color c) and Graphics's setColor(Color c) ?
  5830.  
  5831.      [*] First of all, these methods do the same thing: Set the foreground
  5832.      color to the value of the parameter. The difference lies in where you
  5833.      use them. There is also a Component.setBackground that will set the
  5834.      background color.
  5835.  
  5836.      If you are in a constructor or an event handler (e.g. "click here to
  5837.      turn the canvas blue") you have a Component and should use the
  5838.      setForeground() method. If you are in a paint() method, that takes a
  5839.      Graphics context as its argument so you will typically use
  5840.      g.setColor(c).
  5841.  
  5842.      Unlike a Component, a Graphics object doesn't have a background color
  5843.      and a foreground color that you can change independently. A Graphics
  5844.      object arrives in the color(s) inherited from the drawing surface. From
  5845.      then on, any rendering (drawLine(), drawRect(), fillOval(), etc.) will
  5846.      be done in the setColor() color. Because they do different things, the
  5847.      Component and Graphics methods have different names.
  5848.  
  5849.  32. (Sect. 10) When I start a mouse drag inside a Component, and go outside
  5850.      the Component, still dragging, the mouse events still get sent to the
  5851.      Component, even though I am outside it. Is this a bug?
  5852.  
  5853.      [*] No, it is the specified behavior. The Java API documentation says:
  5854.           "... Mouse drag events continue to get sent to this component even
  5855.           when the mouse has left the bounds of the component. The drag
  5856.           events continue until a mouse up event occurs...."
  5857.      It is done for the convenience and ease of the application programmer.
  5858.      It allows you to handle all drags from the place of origin. If you
  5859.      don't want this, simply look at the coordinates of the mouseDrag Event,
  5860.      and if they are outside the Component, ignore them.
  5861.  
  5862.  33. (Sect. 10) Why doesn't my window close when I click on the X in the
  5863.      title bar?
  5864.  
  5865.      [*] Here's how to make your program do that.
  5866.         o JDK 1.0.2: Handle Event.WINDOW_DESTROY to do a hide() and
  5867.           dispose() on the Frame.
  5868.         o JDK 1.1:
  5869.              + Listen for WindowEvent and do hide(); dispose(); in
  5870.                windowClosing() - this really ought to be the "default"
  5871.                behaviour, so was made so for a Swing JFrame.
  5872.              + Enable AWTEvent.WINDOW_CLOSING and do the hide() and
  5873.                dispose() in processWindowEvent().
  5874.         o JDK 1.2: The Component JFrame does a close by default (see section
  5875.           10).
  5876.  
  5877.  34. (Sect. 10) How can I force a synchronization of the graphics state,
  5878.      e.g. of a cursor change, or an animation frame to be rendered?
  5879.  
  5880.      [*] This is done by the sync() method in Toolkit. So just use:
  5881.  
  5882.      AnyComponent.getToolkit().sync();
  5883.  
  5884.  35. (Sect. 10) How can I tab between components?
  5885.  
  5886.      [*] In JDK 1.0, you have to read the key press, and program it
  5887.      explicitly. JDK 1.1 supports tab and shift-tab (previous field)
  5888.      automatically. The tab order is the order that the components were
  5889.      added to the container.
  5890.  
  5891.  36. (Sect. 10) What is the difference between "low level" and "semantic"
  5892.      events?
  5893.  
  5894.      [*] Low-level events are tied to a specific component (resizing a
  5895.      window, dragging the mouse, striking a key, adding a Component to a
  5896.      Container, etc.). Semantic events are those generated when you frob a
  5897.      control (move a scrollbar, click on a button, select from a menu,
  5898.      etc.), and the same kind of event can be generated by several different
  5899.      components. A Button and a List both fire an Action event when they are
  5900.      clicked on.
  5901.  
  5902.      To the programmer, the important difference is that you can change a
  5903.      low-level event such as the key value in a keypress, and it will
  5904.      display the new value. You can also consume low level events so that
  5905.      they do not appear in the widget. You can't do these things with
  5906.      semantic events - they have already "occurred" to the widget.
  5907.  
  5908.      Semantic events: Use the method addXListener() to add a listener object
  5909.      which implements the XListener interface to get XEvent objects
  5910.      delivered (usually via the AWTEventMulticaster). Low level events: Use
  5911.      the method enableEvents() and override performX() to grab those events
  5912.      in the object itself.
  5913.  
  5914.  37. (Sect. 10) Is it possible to have a Java window float above all other
  5915.      windows. For example, a tool palette floats in a super-layer always
  5916.      above all the regular document windows on which you use the palette's
  5917.      tools?
  5918.      [*] On MS Windows, a Window object floats above all other windows,
  5919.      unlike a Frame, which is layered in with ordinary windows. This
  5920.      behavior yields a "floating" effect. Whether a Window object is really
  5921.      supposed to float is another question entirely.
  5922.  
  5923.      On Mac, a Window object is either layered in with other windows, just
  5924.      like a Frame is, or else it is entirely modal - depending on which VM
  5925.      you use. In Java - there appears to be no easy way to get floating
  5926.      behavior. If anyone knows otherwise, please send in your comments.
  5927.  
  5928.  38. (Sect. 10) How can iconify/deiconify a window in Java?
  5929.  
  5930.      [*] JDK 1.1 had no way to write code to force a window to iconify or
  5931.      deiconify. Support was added in JDK 1.2.
  5932.  
  5933.           MyFrame.setState( Frame.ICONIFIED );
  5934.           MyFrame.setState( Frame.NORMAL );
  5935.  
  5936.      will do the trick. There is a corresponding getState();
  5937.  
  5938.  39. (Sect. 10) How do I know which mouse button was pressed, and how often?
  5939.  
  5940.      [*] To handle mouse events you have to implement the MouseListener
  5941.      interface, or derive from the MouseAdapter class in order to use one of
  5942.      the mouse-handling methods. The MouseEvent argument passed to the
  5943.      handling methods contains fields that say which button was pressed, and
  5944.      the click count. Use code like this.
  5945.  
  5946.      public void mouseClicked(MouseEvent m) {
  5947.       boolean leftButtonPush   =
  5948.          (m.getModifiers() & java.awt.event.InputEvent.BUTTON1_MASK) != 0;
  5949.       boolean centerButtonPush =
  5950.          (m.getModifiers() & java.awt.event.InputEvent.BUTTON2_MASK) != 0;
  5951.       boolean rightButtonPush  =
  5952.          (m.getModifiers() & java.awt.event.InputEvent.BUTTON3_MASK) != 0;
  5953.  
  5954.       int click = m.getClickCount();    // might be 1,2,3 clicks or more
  5955.  
  5956.      You can also call at m.isPopupTrigger(). If it returns a true value,
  5957.      the user has asked for a pop-up menu. On a lot of window systems, the
  5958.      right mouse button is the trigger for pop-up menus.
  5959.  
  5960.      You can overload processMouseEvent for your component.
  5961.  
  5962.      public void processMouseEvent(MouseEvent e) {
  5963.          if (e.isPopupTrigger())  {
  5964.             // do what you want
  5965.          }
  5966.          else
  5967.            super.processMouseEvent(e);
  5968.        }
  5969.  
  5970.      The code above applies to JDK 1.1. You can also call
  5971.      java.awt.swing.SwingUtilities.isRightMouseButton(MouseEvent me).
  5972.  
  5973.      See also question 15.10.
  5974.  
  5975.                        -------------------------------
  5976.  
  5977. 11. Swing
  5978.  
  5979.   1. (Sect. 11) What is Swing?
  5980.  
  5981.      [*] Swing is a new GUI toolkit bundled with JDK 1.2, and available as
  5982.      an add-on extension library for JDK 1.1. Swing is part of the Java
  5983.      Foundation Classes and supports a GUI toolkit that lets developers
  5984.      create components that have a pluggable look-and-feel. From an
  5985.      architectural standpoint, the Swing component set extends - but does
  5986.      not completely replace - the Abstract Windowing Toolkit (AWT).
  5987.  
  5988.      Swing has many components that can be used in place of components in
  5989.      the AWT (e.g. JFrame instead of Frame, JButton instead of Button,
  5990.      JApplet instead of Applet, JPanel instead of Panel). It also has many
  5991.      components that don't exist in the AWT (e.g. tool tips, toolbars, and
  5992.      progress bars). However Swing relies on the underlying AWT being there.
  5993.  
  5994.      The Swing toolkit allows the creation of GUI's that are every bit as
  5995.      sophisticated as native code toolkits like MFC -- with the Java
  5996.      advantage that they run on every platform. The pluggable look and feel
  5997.      means that they can have the same appearance on every platform, or you
  5998.      can choose to have it look like Windows on a PC, like Motif on a Unix
  5999.      box, etc, just as the user chooses.
  6000.  
  6001.      Swing also supports the Accessiblity API. That API allows the adaptive
  6002.      software used by disabled computer users to directly query the Java VM
  6003.      and extract information about the running program, the usual purpose
  6004.      for this being to determine the UI components. Then the existing
  6005.      adaptive software can interpret it to the user (e.g. read the contents
  6006.      of a window, etc). Swing doesn't use native components, and the
  6007.      adaptive software taps into native components, so without the
  6008.      accessibility API has a real role in bringing the two together. The
  6009.      beauty of the Accessibility API is that developers need to do little
  6010.      work to support it, but they do need to be made aware of it if they add
  6011.      new components.
  6012.  
  6013.      With Swing, native window behavior is confined to external window
  6014.      frames (and their borders) and a few other things such as fonts and the
  6015.      buffers used to hold window contents. The composition, layout, and
  6016.      drawing of controls is now all handled by Java code. So identical code
  6017.      is executed to create and manage your user interface on every platform.
  6018.      Swing provides a much greater consistency of behavior across different
  6019.      platforms.
  6020.  
  6021.      Swing works with JDK 1.1 if you download the swing.jar file and add it
  6022.      to your path. Swing is built in to JDK 1.2, and Javasoft has just
  6023.      changed its 1.2 Swing package-naming strategy. It is now called
  6024.      javax.swing.
  6025.  
  6026.   2. (Sect. 11) Should I use Swing or AWT to build my GUIs?
  6027.  
  6028.      [*] Use Swing to build your apps now instead of AWT components,
  6029.      wherever you have a choice. Swing is a GUI toolkit that is at least as
  6030.      good as other commercial GUI toolkits, and better in several respects.
  6031.  
  6032.      With Swing, it is easier to build an application that is portable
  6033.      between Mac, Solaris, Windows 95 and NT, than it is to use Win32 and
  6034.      build an application that just runs on Windows 95 and NT.
  6035.  
  6036.   3. (Sect. 11) Where can I find a Swing tutorial?
  6037.  
  6038.      [*] There is a Swing tutorial at
  6039.      http://java.sun.com/docs/books/tutorial/ui/swing/index.html which is
  6040.      part of this tutorial:
  6041.      http://java.sun.com/docs/books/tutorial/ui/TOC.html
  6042.      There is also a Swing FAQ at http://www.drye.com/java/faq.html
  6043.      See also http://www.codeguru.com/java/Swing/index.shtml
  6044.      There is a Swing Developer Connection website with white papers and
  6045.      examples at http://www.theswingconnection.com/.
  6046.      Please let this FAQ maintainer know about other good Swing tutorials
  6047.      and online resources.
  6048.  
  6049.   4. (Sect. 11) What is the Model/View/Controller paradigm?
  6050.  
  6051.      [*] Model/View/Controller is a design pattern or framework originally
  6052.      developed by Prof. Trygve Reenskaug at Xerox PARC in 1978/9. MVC was
  6053.      developed to allow Smalltalk to conveniently support GUIs.
  6054.  
  6055.      Model/View/Controller is a design pattern used extensively in Swing.
  6056.      Basically, the "model" contains your data, the "view" is the graphical
  6057.      representation, and the "controller" is responsible for the interaction
  6058.      between the other two. As an example, think of visually editing the
  6059.      Tree widget that represents a directory. The display is the view.
  6060.      Selecting a file, and dragging it to the trash can will delete the
  6061.      file. In order for the delete to happen, the controller must tell the
  6062.      model what just happened in the view.
  6063.  
  6064.      In practice, inter-communication between the view and the controller is
  6065.      complex, so the two are bundled together in one category in Swing. The
  6066.      model (data) is separate though.
  6067.  
  6068.      There's a reasonable white paper on MVC in Swing at
  6069.      http://java.sun.com:81/products/jfc/swingdoc-static/swing_arch.html .
  6070.      There is information on other OO design patterns at
  6071.      http://www.parallax.co.uk/cetus/oo_patterns.html.
  6072.  
  6073.   5. (Sect. 11) When I run the Swing demo on Windows 95 I get an error "Out
  6074.      of environment space."
  6075.  
  6076.      [*] That's because you don't have enough space for your DOS
  6077.      environment. You can fix this with:
  6078.         o Right click your MS-DOS Prompt icon or window and choose
  6079.           Properties.
  6080.         o Choose "Memory" and on "Initial Environment", choose 4096 instead
  6081.           of "auto".
  6082.         o Run Swing again, you'll be OK.
  6083.  
  6084.   6. (Sect. 11) How can I run Swing code in a browser?
  6085.  
  6086.      [*] Most current browsers have to be specifically set up to run Swing
  6087.      applets. Read the article at
  6088.      http://www.javasoft.com/products/jfc/swingdoc-current/applets.html for
  6089.      information about this. The article also contains a simple Swing
  6090.      example applet, so you can confirm that that's your problem.
  6091.      Another approach is to use the Java plug-in, which automatically gives
  6092.      a Swing-compatible Java in the browser. See
  6093.      http://java.sun.com/products/jfc/tsc/swingdoc-current/java_plug_in.html
  6094.  
  6095.   7. (Sect. 11) Why is my menu showing up behind other components when I use
  6096.      Swing?
  6097.  
  6098.      [*] The answer relates to lightweight and heavyweight (peer-based)
  6099.      components. There is a good article about it at
  6100.      http://www.javasoft.com/products/jfc/swingdoc-current/mixing.html
  6101.  
  6102.      For those who want the quick fix, and will read the article later,
  6103.      adding the line:
  6104.  
  6105.      javax.swing.JPopupMenu.setDefaultLightWeightPopupEnabled(false);
  6106.  
  6107.      before you create any menus will probably fix it (even if you're using
  6108.      menus other than JPopupMenu).
  6109.  
  6110.      The summary answer is that a Lightweight component will not appear over
  6111.      a heavyweight component by default.
  6112.  
  6113.   8. (Sect. 11) Why is there no JCanvas? How do I get a lightweight Canvas?
  6114.  
  6115.      [*] Use a JPanel as a Swing replacement for Canvas. All Swing
  6116.      components have a paint(Graphics) routine that you can override, just
  6117.      as you would have with Canvas, (but you probably want to override
  6118.      paintComponent(Graphics) instead, see next question).
  6119.  
  6120.   9. (Sect. 11) Why don't the borders of my Swing components look right when
  6121.      I override paint(Graphics)?
  6122.  
  6123.      [*] Swing splits painting into several different routines:
  6124.         o paintComponent(Graphics),
  6125.         o paintBorder(Graphics),
  6126.         o paintChildren(Graphics)
  6127.      all of which are called from paint(Graphics). If you override paint(),
  6128.      unless you remember to do it, the paintBorder() and paintChildren()
  6129.      won't get done.
  6130.  
  6131.      In most cases, what you really want to do is override paintComponent()
  6132.      instead of paint().
  6133.  
  6134.  10. (Sect. 11) Why does my JFrame go away after I choose system close on
  6135.      the window?
  6136.  
  6137.      [*] Assume that you have a Swing JFrame component, and you handle the
  6138.      windowClosing event, but do nothing in the handler. You will see that
  6139.      the JFrame disappears anyway.
  6140.      The reason is that JFrame's have default handling of the system close
  6141.      operation, separate from the windowClosing event. You have to override
  6142.      that by calling:
  6143.  
  6144.         setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
  6145.  
  6146.      on your JFrame.
  6147.  
  6148.  11. (Sect. 11) Why can I run the Mac Look and Feel only on Mac OS?
  6149.  
  6150.      [*] (This answer comes from the Swing Connection, see
  6151.      http://java.sun.com/products/jfc/tsc/swingdoc-current/911.html).
  6152.      Sun has not determined that it has the right to deliver the Mac look
  6153.      and feel on platforms other than MacOS. If Apple were to confirm Sun's
  6154.      right to deliver this look and feel on other operating systems, Sun
  6155.      would be delighted to remove the lock. To date, Apple has declined to
  6156.      do this.
  6157.  
  6158.      Although you cannot use the new Mac L&F on non-Macintosh platforms,
  6159.      there is a way to examine the source code so developers can use it as
  6160.      an example of how to create a custom L&F. The Mac L&F is distributed in
  6161.      "stuffed-binhexed" format, which is standard for the Macintosh. If you
  6162.      develop on a MS-Windows platform and would like to examine the source
  6163.      code for the Mac L&F then you can do that by downloading and using a
  6164.      program called Aladdin Expander for Windows. You can download Aladdin
  6165.      Expander from this URL: http://www.aladdinsys.com/expander/index.html
  6166.      When you have downloaded Aladdin Expander, you can use it to decode the
  6167.      Mac L&F file posted on the JDC.
  6168.  
  6169.      A recent posting on comp.lang.java.gui suggested the following user
  6170.      workaround:
  6171.  
  6172.      import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
  6173.      class MyOwnWindowsLookAndFeel extends WindowsLookAndFeel {
  6174.          public isSupportedLookAndFeel() { return true; }
  6175.      }
  6176.  
  6177.      The desire on Sun's part to avoid infringing the Windows Look and Feel
  6178.      is also the reason why the JTree uses colored circles (and soon, little
  6179.      circles with a short line coming out of them) for the nodes to indicate
  6180.      whether they are open or not. The Swing team could have used the '+'
  6181.      and '-' as Windows does, or even the triangles that MacOS uses, but
  6182.      decided against it.
  6183.  
  6184.  12. (Sect. 11) When I set the cursor to WAIT_CURSOR why does it only change
  6185.      when my cursor is over specific components?
  6186.      or
  6187.      How can I change the cursor to a WAIT_CURSOR over my entire window and
  6188.      all of its components, preventing any user action, while some other
  6189.      process is happening. (i.e. database access, opening another window,
  6190.      downloading an image, sorting some data, etc.)
  6191.  
  6192.      [*] In JDK 1.0.2 only the awt Frame could change its Cursor. With the
  6193.      advent of JDK 1.1 the Cursor manipulation has been move to the
  6194.      Component clss. Now all Components have access to the Cursor class.
  6195.  
  6196.      You could change your Cursor to a WAIT_CURSOR for each Component. This
  6197.      could be time-consuming. You could have a potentially large number of
  6198.      Components. With the advent of the JFC Swing, there is a mechanism to
  6199.      change the Cursor over the entire Window regardless of the number of
  6200.      components. The Swing component JFrame has a method:
  6201.  
  6202.                   public void setGlassPane(Component glassPane)
  6203.  
  6204.      which sets an awt Component as the 'glassPane' for the JFrame.
  6205.  
  6206.      This Component will cover the entire JFrame's visible user accessible
  6207.      (when visible), area excluding the border set by the underlying
  6208.      windowing system. With the 'glassPane' Component you can set the
  6209.      'WAIT_CURSOR' over an entire JFrame, prohibiting user input (the
  6210.      'glassPane' Component gets all user input) and blocking the user until
  6211.      your 'other' processing is complete.
  6212.  
  6213.      NOTE: You must spawn a Thread to accomplish your 'other' work if you
  6214.      want to see the WAIT_CURSOR while the 'other' processing is happening.
  6215.      When the 'other' work is being accomplished, the 'glassPane' is visible
  6216.      with a WAIT_CURSOR and gobbling up all user input. When the 'other'
  6217.      work is finished, the Thread uses your waitCursor() method to hide your
  6218.      'glassPane' until its needed again.
  6219.  
  6220.  13. (Sect. 11) Why does the compiler complain that the
  6221.      javax.swing.ProgressMonitor method "isCancelled()" isn't found?
  6222.  
  6223.      [*] In American English there are two acceptable spellings: "canceled"
  6224.      and "cancelled". Note that the first one has one "el" and the second
  6225.      two "el's". Sun spells this "canceled" for ProgressMonitors but many of
  6226.      the secondary sources of documentation spell it "cancelled". To make
  6227.      matters worse, Sun spells it "cancelled" at other times, such as the
  6228.      method "isCancelled()" for PrinterJob.
  6229.  
  6230.  14. (Sect. 11) Why doesn't pressing the Enter key activate the default
  6231.      button on a Swing dialog?
  6232.  
  6233.      [*] The default keymap for Swing text components (derived from
  6234.      JTextComponent) binds the Enter key (VK_ENTER) to the ActionEvent for
  6235.      text fields. This was done to be compatible with the behavior of
  6236.      java.awt.Textfield. To enable use of the Enter key to activate the
  6237.      default button, remove the Enter key binding from the default text
  6238.      component keymap as follows:
  6239.  
  6240.          static {
  6241.            KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
  6242.            Keymap map =
  6243.                 JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
  6244.            map.removeKeyStrokeBinding(enter);
  6245.          }
  6246.  
  6247.  15. (Sect. 11) How do I create non-rectangular Components?
  6248.  
  6249.      [*] Take a look at the following example that comes with the JDK:
  6250.      $JAVAHOME\demo\awt-1.1\lightweight\RoundButtons\example.html
  6251.  
  6252.                        -------------------------------
  6253.  
  6254. 12. Browsers
  6255.  
  6256.   1. (Sect. 12) When will my favorite browser support Java 1.1?
  6257.  
  6258.      [*] All popular browsers now have JDK 1.1 support. Netscape
  6259.      Communicator 4.04 plus patch "J" fully supports the features of Java
  6260.      1.1. It was released in December 1997, and is only missing the JavaSoft
  6261.      support for applet signing (Netscape has gone its own way on this). See
  6262.      http://developer.netscape.com/support/faqs/champions/java.html#21
  6263.      If you have Netscape 4.05, and the console says anything other than
  6264.      Java 1.1.5 then you do not have a fully 1.1 compliant Netscape. There
  6265.      is a special preview version available here:
  6266.      http://developer.netscape.com/software/jdk/download.html
  6267.  
  6268.      Netscape badly fumbled its Java support in 1997 as its market was
  6269.      seized by Microsoft. Microsoft is using IE as a strategic tool to
  6270.      deploy what Microsoft employees call "polluted Java". For both of these
  6271.      browsers, the Java Plug-in is currently a good approach.
  6272.  
  6273.      Sun's HotJava browser fully supports the JDK 1.1 features. People who
  6274.      are obliged to use a browser without standard Java support should use
  6275.      the Java Plug-In. The Java Plug-In substitutes a standard Java virtual
  6276.      machine for the one that shipped with the browser. It allows you to use
  6277.      RMI, JavaBeans components, and Java Foundation Classes in Internet
  6278.      Explorer 3.02, 4.0, and 4.01. The Java Plug-In also works flawlessly
  6279.      with Netscape browsers. You can download the Java Plug-In from
  6280.      http://java.sun.com/products/.
  6281.      Note that you need to change the HTML a little, to ensure that the
  6282.      plug-in JVM is invoked, not the browser JVM. A tool is included to do
  6283.      the changes automatically.
  6284.  
  6285.   2. (Sect. 12) What applet routines get called in various browsers and the
  6286.      plug-in on different browsing actions (back, forward, load, etc)?
  6287.  
  6288.      [*] Java supporter Dave Postill did the work to get this answer.
  6289.      The life cycle of an applet is illustrated by logging calls to init(),
  6290.      start(), stop() and destroy(). Use caution when your applets have
  6291.      threads since in most sample applet code, the stop() method calls stop
  6292.      on any separate threads within the applet, and then sets them to null.
  6293.  
  6294.      This reckless threadicide is because most people think of the stop()
  6295.      method as something called only when the user leaves the page and wants
  6296.      to forget about it. But since Netscape calls stop() when you resize the
  6297.      window, your users would lose the applet's state when they thought they
  6298.      were only making a minor adjustment.
  6299.  
  6300.      See "Java Tip 8: Threads, Netscape, and the resize problem - How to
  6301.      deal with applet resizing in Netscape Navigator", JavaWorld
  6302.      http://www.javaworld.com/javatips/jw-javatip8.html. Sadly the JavaWorld
  6303.      workaround does not completely fix the problem, since it relies on
  6304.      start() being called soon after stop() to identify a resize. However if
  6305.      you minimise the browser it may send a stop() to the Applet and then
  6306.      may not send a start() until the Browser is either restored or
  6307.      maximised. In this case, using the workaround results in the Applet
  6308.      being destroyed following minimising of the Browser - unless the
  6309.      Browser gets un-minimised within the killThreads timeout.
  6310.  
  6311.                Netscape    Netscape    Applet-    Internet    Internet
  6312.                [4.04/JDK   with        Viewer     Explorer 4  Explorer
  6313.                1.1.4]      Plug-In     [JDK       SP1         with Plug-In
  6314.                [4.05/JDK   [4.05/ JDK  1.1.5]     4.72.3110.8 [5.00.0518.10
  6315.                1.1.5]      1.1.5/      [JDK       on NT 4.0   / Plugin 1.1]
  6316.                            Plugin 1.1] 1.1.6]     SP3         on NT 4.0 SP3
  6317.       1. Clear
  6318.       browser  nothing     nothing     nothing    nothing     nothing
  6319.       cache
  6320.                init(),
  6321.       2.       start() or
  6322.       Initial  init(),     init(),     init(),    init(),     init(),
  6323.       load of  start(),    start()     start()    start()     start()
  6324.       .html    stop(),
  6325.                start() [1]
  6326.  
  6327.       3. Back  stop()      stop(),     [4]        stop(),     stop(),
  6328.                            destroy()              destroy()   destroy()
  6329.       4.                   init(),                init(),     init(),
  6330.       Forward  start()     start()     [4]        start()     start()
  6331.                stop(),     stop(),                stop(),     stop(),
  6332.       5. Reloaddestroy(),  destroy(),  [4]        destroy(),  destroy(),
  6333.                init(),     init(),                init(),     init(),
  6334.                start()     start()                start()     start()
  6335.       6.
  6336.       <shift>
  6337.       reload   stop(),     stop(),                stop(),     stop(),
  6338.       [NS],    destroy(),  destroy(),  [4]        destroy(),  destroy(),
  6339.       <ctrl>   init(),     init(),                init(),     init(),
  6340.       reload   start()     start()                start()     start()
  6341.       [IE]
  6342.  
  6343.       7. Resizestop(),     [3]         [3]        [3]         [3]
  6344.                start()
  6345.       8.
  6346.       Minimize [2]         [3]         stop()     [2]         [3]
  6347.       9.
  6348.       Restore  [2]         [3]         start()    [2]         [3]
  6349.  
  6350.       10. Exit stop(),     stop(),     stop(),    stop(),     stop(),
  6351.                destroy()   destroy()   destroy()  destroy()   destroy()
  6352.  
  6353.      Notes:
  6354.      [1] Results not repeatable.
  6355.      [2] Not tested.
  6356.      [3] Tested, and found that no logged methods are called.
  6357.      [4] Test not applicable.
  6358.  
  6359.   3. (Sect. 12) Is it possible to set and retrieve cookies from Java, in a
  6360.      manner that is compatible with all browsers supporting cookies?
  6361.  
  6362.      [*] Short answer: no.
  6363.      Longer answer: probably no.
  6364.      Ultimate answer:
  6365.      A cookie is a morsel of tasty data that a server sends back to the
  6366.      client, and can retrieve on demand. It allows the server to retain some
  6367.      state information for each of its clients. The information is typically
  6368.      something like "what pages has the user seen?" or "is this a privileged
  6369.      user?".
  6370.      The DevEdge site on Netscape's home page has a Javascript-Java example
  6371.      on getting cookies. Also
  6372.      http://www.geocities.com/SiliconValley/Vista/1337 has info on
  6373.      connecting an applet with JavaScript functions. It's quite involved.
  6374.      Stick to just Java if you can.
  6375.  
  6376.   4. (Sect. 12) I am developing an applet and testing it in Netscape
  6377.      Navigator. I find that after I recompile, I press reload, clear the
  6378.      caches, retype the URL of the HTML wrapper, and I still have the old
  6379.      version. Why is this?
  6380.  
  6381.      [*] Note: a reader reports that as of Netscape Communicator 4.05 it is
  6382.      possible to force the browser to reload the applet by holding down
  6383.      "control"+"shift" while clicking "Reload"
  6384.      In the past Netscape has completely failed to improve the defective
  6385.      code that does this monstrously wrong thing. It has been like this for
  6386.      many successive releases.
  6387.      Flushing the network cache will make no difference; that isn't where
  6388.      the caching is taking place. Although applets are sometimes "pruned"
  6389.      and their ClassLoaders garbage-collected, this doesn't happen
  6390.      predictably, so restarting Netscape is the only reliable work-around at
  6391.      the moment.
  6392.      A related question is "how do I make the browser reload from a
  6393.      URLConnection instead of just getting the content from the local
  6394.      cache?" The answer is to use
  6395.  
  6396.         java.net.URLConnection.setUseCaches(false)
  6397.  
  6398.      Browsers seem to vary in their conformance to this programmatic
  6399.      request. Netscape caching varies depending on whether a proxy server is
  6400.      in use, and which thread in the applet made the get request.
  6401.  
  6402.      Another approach is adding "?" to the URL, e.g.
  6403.  
  6404.  
  6405.            http://www.somesite.com/webcam/image.jpg?100
  6406.  
  6407.      and increasing this number each time the Applet fetches the image.
  6408.  
  6409.   5. (Sect. 12) Why didn't Netscape reload the applet when you pressed the
  6410.      Reload button?
  6411.  
  6412.      [*] For the applet to be reloaded, the new version would have to be
  6413.      loaded in a different ClassLoader. Navigator/Communicator's policy for
  6414.      assigning ClassLoaders to applets doesn't take into account whether a
  6415.      reload has been done (although there is no technical reason why it
  6416.      couldn't).
  6417.      Some versions of Netscape reload the Applet if you use
  6418.      Edit/Preferences/Advanced/Cache to Clear Memory Cache and Clear Disk
  6419.      Cache, then <Shift> while you click on reload.
  6420.      In Explorer, use View/Options/General/Delete Files, then <Control>
  6421.      'Reload' button to reload the page containing the applet.
  6422.  
  6423.      Until they fix it, use the appletviewer to test applets. And send them
  6424.      mail - developers can only fix the bugs they know about.
  6425.  
  6426.   6. (Sect. 12) Should I use Microsoft CAB files or Java JAR files?
  6427.  
  6428.      [*] The question contains its own answer.
  6429.      CAB format is a Microsoft-only format. So do not use it as it destroys
  6430.      software portability.
  6431.      JAR format is the Java standard format, based on PKZIP format including
  6432.      data compression. JARs were introduced with JDK 1.1.
  6433.      See http://www.ibm.com/java/community/viewarchive4.html for more
  6434.      information.
  6435.      You should use the Java standard format JAR (Java Archive) files, not a
  6436.      vendor-specific format. JAR files are not just a Java standard, they
  6437.      are in industry-standard PKZIP format. One reader comments that both
  6438.      formats can be used with this tag:
  6439.           <APPLET NAME=myapplet
  6440.           ARCHIVE="myzip.zip"
  6441.           CODE="com/nnnnn/nnnn/cccccccc.class"
  6442.           WIDTH=n
  6443.           HEIGHT=n>
  6444.           <PARAM NAME="cabbase" VALUE="mycab.cab">
  6445.           </APPLET>
  6446.      IE3 does not support JAR
  6447.      IE4 supports compressed and uncompressed JAR, but not signed JAR
  6448.  
  6449.   7. (Sect. 12) How can I tell the version of Java that my browser supports?
  6450.  
  6451.      [*] See http://java.rrzn.uni-hannover.de/insel/beispiele/vertest.html.
  6452.      This page tells you whether your browser supports JDK 1.1.
  6453.  
  6454.      See http://www.uni-kassel.de/~pfuetz/Properties.html This page tells
  6455.      you which classes you may expect to be present in the browser's
  6456.      runtime.
  6457.  
  6458.   8. (Sect. 12) How can I tell the options/commands that Netscape's JVM
  6459.      takes?
  6460.  
  6461.      [*] You can open the Java Console and type a "?" to get a list of all
  6462.      the commands/options available to you in Netscape's built-in JVM.
  6463.  
  6464.                        -------------------------------
  6465.  
  6466. 13. Applets
  6467.  
  6468.   1. (Sect. 13) What is the difference between an application, an applet,
  6469.      and a servlet?
  6470.  
  6471.      [*] An applicationis a standalone program.
  6472.      An applet is a downloadable program that runs in a web browser.
  6473.      Typically an applet has restricted access to the client system for
  6474.      reasons of security. Other than that it is virtually no different from
  6475.      a regular Java program.
  6476.      A servlet is a Java program whose input comes from a server and whose
  6477.      output goes to a server. Other than that it is virtually no different
  6478.      from a regular Java program. Think of a servlet as an application, but
  6479.      one that (like an applet) requires a context in which to run, namely
  6480.      web server software. Servlets are used like CGI scripts, but take much
  6481.      less processor resources, and they allow the server end to be written
  6482.      in Java as well as the client. There is a page with much servlet
  6483.      information at: http://www.frontiernet.net/~imaging/servlets_intro.html
  6484.  
  6485.      There is a servlet tutorial at
  6486.      http://java.sun.com/docs/books/tutorial/servlets/index.html
  6487.      and another servlet tutorial at
  6488.      http://www.novocode.com/doc/servlet-essentials/
  6489.      There is a servlet FAQ at http://www.saint-elie.com
  6490.  
  6491.      The web server starts up a servlet when the URL is referenced, and now
  6492.      your applets have something that they can talk to (via sockets) on the
  6493.      server that can write files, open connections to other servers, or
  6494.      whatever.
  6495.      There is also a software technology from IBM called an "Aglet".
  6496.      An aglet is a mobile agent that can go from machine to machine,
  6497.      performing tasks, serializing data collected, and "shipping itself"
  6498.      (code and data) to the next machine. It's too early to say if aglets
  6499.      are a flash in the pan or a dawning technology. Read about aglets at
  6500.      http://www.trl.ibm.co.jp/aglets/
  6501.      Finally, there is the ticklet (Tcl/Tk) plugin for your browser
  6502.      (Netscape or Explorer) available at http://sunscript.sun.com/plugin/
  6503.      Don't confuse Sun's JWS "Java Web Server" with JWS "Java Workshop".
  6504.      Java Web Server supports servlets, as does the lightweight and free
  6505.      server at Acme.com:
  6506.      http://www.acme.com/java/software/Acme.Serve.Serve.html
  6507.  
  6508.   2. (Sect. 13) My applet works on my machine, but fails when I put it on
  6509.      our web server. Why?
  6510.  
  6511.      [*] It could be one of several reasons, and unfortunately the messages
  6512.      that you get in this situation aren't much help. In general, you can
  6513.      assume that either your applet's class files are corrupted somehow, or
  6514.      the web server can't find one or more of them when the browser needs
  6515.      them.
  6516.      Be careful of the following things:
  6517.         o Make sure you transfer the class files in binary mode, rather than
  6518.           text or ASCII mode. An error from the browser saying "cannot start
  6519.           applet ... bad magic number" usually means that one of the class
  6520.           files on the server is corrupted. Replace your class binary files
  6521.           on the web server, clean up the cache of your browser, and reload
  6522.           your applet.
  6523.         o Make sure you transfer all of the class files that are a part of
  6524.           your applet. Sometimes people are surprised by how many there are.
  6525.           There will be a class file for every class and interface you
  6526.           define, even if you define more than one in a single source file.
  6527.           If you use the Java 1.1 "inner classes" feature, there will be
  6528.           class files for each inner class as well.
  6529.         o Make sure you maintain the appropriate case distinctions in your
  6530.           filenames. If a class is called StUdLy, it must be found in a file
  6531.           called StUdLy.class.
  6532.         o Make sure you maintain the directory structure that matches your
  6533.           package structure. If you declare a class in package com.foo.util,
  6534.           the class either needs to be in a Jar file, or the class file
  6535.           needs to be in directory com/foo/util under the applet's codebase
  6536.           directory. Again, case distinctions are important for
  6537.           package/directory names, just as they are for class/file names.
  6538.         o Make sure that the web server process will have read access to the
  6539.           class files, and search access to the directories that the files
  6540.           are in. For example, if the web server runs on a Unix machine, use
  6541.           the command "chmod o+r filename" for the files, and "chmod o+x
  6542.           dirname" for the directories.
  6543.  
  6544.   3. (Sect. 13) How do I load a webpage using an applet?
  6545.  
  6546.      [*] Use code like this,
  6547.  
  6548.      getAppletContext().showDocument(
  6549.                     new URL("http://www.here.com") );
  6550.  
  6551.      Or, to show the page in another window or frame,
  6552.  
  6553.      getAppletContext().showDocument(
  6554.              new URL("http://www.here.com"), "windowname" );
  6555.  
  6556.   4. (Sect. 13) How do I use an image as the background to my applet? How do
  6557.      I set the background color of my applet the same as the browser?
  6558.  
  6559.      [*] You can simply do a g.drawImage(yourImage, x, y, this) in the
  6560.      paint() routine of your applet. If the image isn't big enough to fill
  6561.      the entire background, tile it or scale it. Here is some code to tile
  6562.      it
  6563.  
  6564.          // The background image is named "bg".
  6565.          int w = 0, h = 0;
  6566.          while (w < size().width) {
  6567.              g.drawImage(bg, w, h, this);
  6568.              while ((h + bg.getHeight(this)) < size().height) {
  6569.                  h += bg.getHeight(this);
  6570.                  g.drawImage(bg, w, h, this);
  6571.              }
  6572.              h = 0;
  6573.              w += bg.getWidth(this);
  6574.          }
  6575.  
  6576.      Alternatively, the AWT can scale your background image to the size of
  6577.      the applet. The result quality will depend on the kind of image. Inside
  6578.      an applet class, you can use:
  6579.  
  6580.         drawImage(img, 0, 0, size().width, size().height, this);
  6581.  
  6582.      You can set the background color to match the background color of the
  6583.      browser by passing the value in as a parameter, like this:
  6584.           In the HTML applet tag:
  6585.                <param name=BrowserColor value=F1F1F1>
  6586.                (value should be the same hex as the HTML COLOR value).
  6587.           In the Applet init() method:
  6588.  
  6589.               String colparam = getParameter("BrowserColor");
  6590.               int col = Integer.valueOf(colparam,16).intValue();
  6591.               setBackground( new Color(col) );
  6592.  
  6593.      An applet cannot override the size imposed by the HTML. If you make the
  6594.      applet larger, the browser will still clip to the original size. If you
  6595.      need more room, open up a new Frame, Window or Dialog to show your
  6596.      output.
  6597.  
  6598.   5. (Sect. 13) How do you make the applet's background transparent?
  6599.  
  6600.      [*] There is no way to give an applet a transparent background that
  6601.      lets the web browser background show through. You can simulate it by
  6602.      giving the applet a background that matches the underlying browser
  6603.      background. (For a straight color, it will be the value of <BODY
  6604.      BGCOLOR=nnnnnn> in the HTML file). It doesn't produce satisfactory
  6605.      results with a patterned background because of problems aligning the
  6606.      edges.
  6607.      Lightweight components (new in JDK 1.1) have a transparent background,
  6608.      but that merely allows other components to show through. A lightweight
  6609.      component is always ultimately positioned in a heavyweight component.
  6610.  
  6611.   6. (Sect. 13) How do you do file I/O from an applet?
  6612.  
  6613.      [*] Unsigned applets are simply not allowed to read or write files on
  6614.      the local file system (see answer to question 7.8).
  6615.  
  6616.      Unsigned applets can, however, read (but not write) non-class files
  6617.      bundled with your applet on the server, called resource files.
  6618.  
  6619.      See answer to question 7.8 and question 7.9.
  6620.  
  6621.   7. (Sect. 13) How do I pull a non-class file, such as a .gif, out of a jar
  6622.      file?
  6623.  
  6624.      [*] [Question has been retired, in favor of question Q7.9]
  6625.  
  6626.   8. (Sect. 13) How do I read a text file stored in a Jar?
  6627.  
  6628.      [*] [Question has been retired in favor of Q7.9]
  6629.  
  6630.   9. (Sect. 13) How do you get a Menubar/Menu in an applet?
  6631.  
  6632.      [*] In your applet's init() method, create a Frame instance and then
  6633.      attach the Menus, Menubar etc to that frame. You cannot attach the Menu
  6634.      or a Menubar to an applet directly.
  6635.      Or get the parent Frame like this (doesn't work in all execution
  6636.      environments):
  6637.  
  6638.          Container parent = getParent();
  6639.          while (! (parent instanceof Frame) )
  6640.              parent = parent.getParent();
  6641.          Frame theFrame = (Frame) parent;
  6642.  
  6643.      This second suggestion definitely doesn't work in the appletviewer, and
  6644.      probably won't work on Macs (where would the Menubar go?) or in some
  6645.      browsers. In JDK 1.1, just use a popup menu, which isn't attached to a
  6646.      Frame.
  6647.  
  6648.  10. (Sect. 13) Can I get rid of the message "Warning:Applet Window" along
  6649.      the bottom of my popup windows in my Applet?
  6650.  
  6651.      [*] This is a security feature that prevents the applet programmer from
  6652.      popping up a window that looks like it came from the native OS and
  6653.      asking for passwords or credit card info (etc.). Users must always be
  6654.      aware of when they are talking to an unsigned applet. You can get rid
  6655.      of it by signing the applet, if the user accepts signed applets from
  6656.      you. In Netscape (only), using the Capabilities API to make the call
  6657.  
  6658.         PrivilegeManager.enablePrivilege("UniversalTopLevelWindow");
  6659.  
  6660.      before creating the Frame eliminates the message, if the security
  6661.      manager passes it.
  6662.  
  6663.  11. (Sect. 13) When I subclass Applet, why should I put setup code in the
  6664.      init() method? Why not just a constructor for my class?
  6665.  
  6666.      [*] The browser invokes your constructor, then setStub, then init().
  6667.      Hence when your constructor is invoked, the AppletStub (and through it
  6668.      the AppletContext) is not yet available. Although in principle you can
  6669.      do things in the constructor that don't rely (even indirectly) on the
  6670.      AppletStub or AppletContext, it is less error-prone to simply defer all
  6671.      setup to the init() method. That way you know that anything that needs
  6672.      the stub/context will have it available.
  6673.  
  6674.  12. (Sect. 13) I want to know about {applets,applications} but the lousy
  6675.      book I got just talks about {applications,applets}. What can I do?
  6676.  
  6677.      [*] The truth is that 95% of the material is the same, whichever your
  6678.      book chooses to focus on. Some people write their apps to work
  6679.      completely in a Panel, then depending on whether they're running
  6680.      stand-alone or in a browser the Panel is either added to a Frame or an
  6681.      Applet. The trick is that you need to add a listener to the
  6682.      application's Frame to handle the WINDOW_CLOSING (previously
  6683.      WINDOW_DESTROY) event yourself.
  6684.      If you fail to do this, when running as an application, the window
  6685.      won't close. See Question 15.7 for a sample of the right handler.
  6686.      In this scenario the following code will tell you which environment
  6687.      you're running in:
  6688.  
  6689.         public boolean isRunningInBrowser() {
  6690.              Component p = getParent();
  6691.              while(p != null && !(p instanceof Frame)) {
  6692.                  p = p.getParent();
  6693.              }
  6694.              return (p == null);
  6695.          }
  6696.  
  6697.  13. (Sect. 13) How do I print a page with an applet?
  6698.  
  6699.      [*] Browsers are starting to introduce support for this. Until they all
  6700.      have it, your best bet is to print a screendump. Using the browser to
  6701.      print the page may leave a blank where the applet is. Putting print
  6702.      support in the applet will print the applet only, not the rest of the
  6703.      browser page.
  6704.      Also in the FAQ: Q5.2.
  6705.  
  6706.  14. (Sect. 13) How can I position my dialogs centered (not top left)?
  6707.  
  6708.      [*] Use some code like this:
  6709.  
  6710.          void center(Component parent) {
  6711.              pack();
  6712.              Point p = parent.getLocation();
  6713.              Dimension d = parent.getSize();
  6714.              Dimension s = getSize();
  6715.              p.translate((d.width - s.width) / 2, (d.height - s.height) / 2);
  6716.              setLocation(p);
  6717.          }
  6718.  
  6719.  15. (Sect. 13) How can I get two applets on the same page to communicate
  6720.      with each other?
  6721.  
  6722.      [*] This is the purpose of the InfoBus protocol. See
  6723.      http://java.sun.com/beans/infobus/index.html
  6724.  
  6725.      The older way to do it was as follows. In your HTML page, give a NAME
  6726.      in the APPLET tag for the applet receiving the message, say <APPLET ...
  6727.      NAME=someName ...>. In the Java code of the other applet do
  6728.  
  6729.          Applet anotherApplet = getAppletContext.getApplet("someName");
  6730.  
  6731.      Cast anotherApplet to the correct applet subclass, and you can call any
  6732.      methods in the applet subclass. Don't forget to use appropriate
  6733.      synchronization when two threads tweak variables. This only works when
  6734.      the applets are truly on the same page. If they are in different
  6735.      frames, it doesn't work.
  6736.      You can walk through all the applets on an HTML page using code like
  6737.      that below. However this appears to be broken in Communicator 4.04 on
  6738.      Win95.
  6739.  
  6740.      Applet otherApplet;
  6741.      AppletContext ac =getAppletContext;
  6742.      Enumeration applets = null;
  6743.      for (applets=ac.getApplets(); applets.hasMoreElements(); ) {
  6744.          otherApplet=(Applet)applets.nextElement();
  6745.          if (otherApplet!=this) break;
  6746.          // do something with otherApplet, e.g.
  6747.          // if (otherApplet instanceof FooApplet) ...
  6748.      }
  6749.  
  6750.      Some people suggest using the static members of a common class to
  6751.      communicate information between the applets. This is not recommended as
  6752.      it relies on class-loading behavior that may change in future. Netscape
  6753.      changed it in one Beta so it didn't work, then changed it back again so
  6754.      it did. It doesn't work if you use the "mayscript" tag though.
  6755.      Inter-applet communication sometimes arises when you have a
  6756.      multi-screen type program and you don't want to force the user into
  6757.      downloading everything at once. One alternative is to make them into
  6758.      one applet with two GUIs. Try to avoid the need for applets to talk to
  6759.      each other. Also check the URL
  6760.      http://java.sun.com:81/products/hotjava/1.1/applet_environment.html
  6761.      which explains how it can be done in HotJava 1.1. Recommendation: avoid
  6762.      code which is browser-specific.
  6763.  
  6764.  16. (Sect. 13) How can I resize an applet?
  6765.  
  6766.      [*] If you want resizing behavior from an applet, you should launch an
  6767.      external Frame that can be resized independently.
  6768.      One programmer suggests using percentages for the height/width
  6769.      parameters in an applet tag, like this:
  6770.  
  6771.          <APPLET CODE="lewinsky.class" WIDTH="100%" HEIGHT="100%">
  6772.  
  6773.  
  6774.      You can't resize the applet directly, but it does get resized when you
  6775.      resize the browser window (tested with Netscape 3.04 and 4.04, but does
  6776.      not work with appletviewer). If you have nothing else on your HTML page
  6777.      and use 100% for your width and height, the browser window looks almost
  6778.      like a real application.
  6779.      For the extremely tricky: have the browser reload the page with the
  6780.      applet when the browser resizes using new values for width and height
  6781.      (probably not what you want most of the time). You would need
  6782.      Javascript to generate a page dynamically using document.write("...")
  6783.      when the browser resizes. Not recommended. Another possibility is to
  6784.      use the new SplitPane class in JFC.
  6785.  
  6786.  17. (Sect. 13) How do I sign an applet?
  6787.  
  6788.      [*] The browser vendors have produced independent and different
  6789.      solutions for applet signature (alas). Here are some URLs on this
  6790.      topic.
  6791.  
  6792.      See the Java Signing FAQ at
  6793.      http://www.fastlane.net/~tlandry/javafaq.txt
  6794.  
  6795.      Read the basics of signing at:
  6796.      http://www.javareport.com/html/features/archive/9802/somers.shtml
  6797.      Be aware that the mechanism of signing and administering signed code
  6798.      changed significantly between Java 1.1 and Java 2.
  6799.  
  6800.      Netscape signing:
  6801.      http://developer.netscape.com/docs/manuals/signedobj/javadoc/netscape_security_Target.html
  6802.  
  6803.      https://certs.netscape.com/client.html
  6804.      http://developer.netscape.com/docs/manuals/signedobj/capabilities/contents.htm
  6805.  
  6806.      http://developer.netscape.com/docs/manuals/signedobj/targets/contents.htm
  6807.  
  6808.      Microsoft signing:
  6809.      http://www.microsoft.com/java/security/secfaq.htm
  6810.      http://www.microsoft.com/java/sdk/20/tools/signcode.htm
  6811.  
  6812.                        -------------------------------
  6813.  
  6814. 14. Multi-Media
  6815.  
  6816.   1. (Sect. 14) Are there any good Java Image libraries?
  6817.  
  6818.      [*] Yes. Try the Java Image Management Interface (JIMI), which offers a
  6819.      free trial period. JIMI is a toolkit that lets your Java programs read
  6820.      and write many graphics file formats (PNG, JPG, BMP, GIF etc). JIMI is
  6821.      written in 100% Java, and best of all, it's a breeze to get started
  6822.      with. See http://www.activated.com/jimi.html
  6823.  
  6824.   2. (Sect. 14) Why won't my audio file play?
  6825.  
  6826.      [*] Java 1.1 and earlier releases use one audio format exclusively. The
  6827.      audio file must be in .au format, recorded at 8 KHz, mono, in mu-law
  6828.      encoding. If your audio clip is in a different format (e.g., .wav) or a
  6829.      different frequency it must be converted to the exact specifications
  6830.      above before Java can play it. Support for .wav and other formats is
  6831.      part of the Java Media Framework coming in JDK 1.2.
  6832.      Search at http://www.yahoo.com for GoldWave for Win 95, sox for Unix
  6833.      and similar conversion utilities for other systems.
  6834.      Other sites:
  6835.         o One conversion utility in Java is at
  6836.           http://saturn.math.uaa.alaska.edu/~hursha
  6837.         o The source of a Java class to play linear PCM .WAV files is at:
  6838.           http://www.shef.ac.uk/~cs1mjp/Java/WhiteBoard/WavePlayer.html. It
  6839.           can be used in any Java application or applet.
  6840.  
  6841.   3. (Sect. 14) How can I do video streaming using Java?
  6842.  
  6843.      [*] That is the purpose of StreamBean. See
  6844.      http://www.streambean.com/streambean/
  6845.  
  6846.   4. (Sect. 14) Does Java support animated GIFs?
  6847.  
  6848.      [*] Java 1.0.2 and earlier releases use GIF and JPEG formats, and do
  6849.      not use the GIF89 animated GIF format. (An animated GIF is one that
  6850.      contains successive frames of an image, so when they are displayed in
  6851.      quick sequence the image appears to contain movement). When you display
  6852.      an animated GIF in Java 1.0.2, you will just get the first frame. There
  6853.      doesn't appear to be any easy way to get other frames from the image.
  6854.      The advantage of an animated GIF file is that there is only one file to
  6855.      download, and it is simple to do simple animations. The advantage of
  6856.      programmatic control over individual frames is that you control the
  6857.      rate and order of displaying them.
  6858.      Here's a surprise: JDK 1.1 supports the animated display of animated
  6859.      GIFs. For simple animations animated GIFs are a lot easier and
  6860.      lighter-weight than coding an animation explicitly.
  6861.  
  6862.   5. (Sect. 14) How do I create animated GIFs?
  6863.  
  6864.      [*] Use GIFanimator from ULead (said to be the best)
  6865.      http://www.ulead.com, or GIF Construction Set from Alchemy Mindworks
  6866.  
  6867.   6. (Sect. 14) How do I prevent animated GIFs from flashing while
  6868.      displaying?
  6869.  
  6870.      [*] The problem is most likely that in your paint method you have
  6871.  
  6872.          g.drawImage(img, ix, iy, this);
  6873.  
  6874.  
  6875.      You should change this to
  6876.  
  6877.          g.drawImage(img, ix, iy, getBackground(), this);
  6878.  
  6879.  
  6880.      This will change all the transparent regions of the image to the
  6881.      background color before painting to the screen. If you paint
  6882.      transparent images directly to the screen they flicker.
  6883.      If that does not solve it then check that imageUpdate is
  6884.  
  6885.      public boolean imageUpdate(Image img, int flags, int x, int y,
  6886.                    int width, int height) {
  6887.              if ((flags & (FRAMEBITS|ALLBITS))!= 0) repaint();
  6888.              return (flags & (ALLBITS|ABORT)) == 0;
  6889.      }
  6890.  
  6891.  
  6892.      update is
  6893.  
  6894.          public void update(Graphics g) { paint(g); }
  6895.  
  6896.  
  6897.      If you have a background Image behind the partly transparent animated
  6898.      GIF you will have to double buffer. You can crop the backgound image so
  6899.      you won't have to double buffer the full app and waste too much memory.
  6900.  
  6901.   7. (Sect. 14) Does Java support transparent GIFs?
  6902.  
  6903.      GIF89a images with a transparent background show up as transparent
  6904.      without further filtering. This has been supported from 1.0 on. Java
  6905.      correctly displays both animated GIFs and transparent GIFs.
  6906.      Even better, you can fill the transparent pixels with a color (so they
  6907.      appear non-transparent in Java). Just pass the fill color explicitly:
  6908.  
  6909.          drawImage(img, x, y, w, h, fillcolor, this);
  6910.  
  6911.  
  6912.      Further, you can filter the pixels of an Image to turn any bits you
  6913.      wish transparent. However, the most you can do is reveal what is
  6914.      underneath the image. You cannot reveal what is underneath the applet
  6915.      (i.e. on the browser itself). By default applets have a plain grey
  6916.      background.
  6917.   8. (Sect. 14) How do I play video in Java?
  6918.  
  6919.      [*] Use the Java Media Framework Player API.
  6920.      Other sites:
  6921.         o The Java Media Framework Player API spec can be found at
  6922.           http://java.sun.com/products/java-media/jmf/
  6923.         o Intel has released a SDK for the Java Media Framework Player API.
  6924.           The SDK is for Windows 95 and Windows NT. For more information,
  6925.           see http://developer.intel.com/ial/jmedia
  6926.         o SGI has released an implementation of JMF for IRIX: See
  6927.           http://www.sgi.com/Products/motion/
  6928.  
  6929.   9. (Sect. 14) How can I play *.au files from an application?
  6930.  
  6931.      [*] A new static method was introduced in JDK1.2 in the class Applet:
  6932.  
  6933.          public final static AudioClip newAudioClip(URL url) {
  6934.  
  6935.  
  6936.      The method turns a URL (pointing to an audio file) into an AudioClip.
  6937.      Since the method is static it can be used without any objects of class
  6938.      Applet needing to exist, e.g. in an application. Once you have an
  6939.      AudioClip, you can play it with:
  6940.  
  6941.          MyAudioClip.play();
  6942.  
  6943.  
  6944.      The Java Media Framework provides a richer API for playing sounds in an
  6945.      application.
  6946.      For code prior to JDK 1.2, you can use the AudioClip or AudioPlayer
  6947.      class in sun.audio
  6948.      http://www.javaworld.com/javaworld/javatips/jw-javatip24.html. If you
  6949.      do this your code is no longer 100% pure Java, as it relies on a vendor
  6950.      library.
  6951.  
  6952.          import sun.audio.*;
  6953.  
  6954.  
  6955.          URL url; ...
  6956.          AudioStream audiostream = new AudioStream(url.openStream());
  6957.          AudioPlayer.player.start(audiostream);
  6958.          ...
  6959.          AudioPlayer.player.stop(audiostream);
  6960.  
  6961.  
  6962.      Also in the FAQ:
  6963.      Use the new Java Media Framework API, allowing a wide range of video
  6964.      and audio formats to be played back. See previous question.
  6965.  
  6966.  10. (Sect. 14) How do I read in an image file, in an application?
  6967.  
  6968.      Use
  6969.  
  6970.          Image img = Toolkit.getDefaultToolkit().getImage(fname);
  6971.  
  6972.  
  6973.  11. (Sect. 14) When I initialize a component,I call MyComponent.getImage()
  6974.      to get its image. createImage() returns null! I know the image works
  6975.      elsewhere. What's wrong?
  6976.  
  6977.      [*] A peer component needs to exist for your component before you can
  6978.      get its image. This is done by the method addNotify() (surely one of
  6979.      the most poorly named methods in all Java -- it doesn't mean "add a
  6980.      Notify". It means "Notify that the Component has been added to a
  6981.      Container". It tells the system, "you need to create the peer for this
  6982.      Component now"). addNotify will be called for you when you add your
  6983.      component to a container.
  6984.      Javasoft notes that most applications do not call addNotify() directly.
  6985.      It is called for you when you add the component to a container. If you
  6986.      have any code that requires peer resources, you can move it into a
  6987.      thread that is started from a conditional branch of the paint() or
  6988.      update() method. That way the peer will definitely exist when the code
  6989.      is executed.
  6990.      A common reason for seeming to require peer resources in a constructor,
  6991.      or alternatively in the getPreferredSize() method, (which is also
  6992.      usually before the peer is created) is to measure the area required for
  6993.      your window, in terms of font and image sizes. Font sizes may be
  6994.      obtained by calling
  6995.      Toolkit.getDefaultToolkit().getFontMetrics(somefont). This does not
  6996.      require a peer. Image sizes may be obtained by waiting for the relevant
  6997.      Image to load from the ImageProducer by using an ImageObserver, or a
  6998.      MediaTracker (see 8.15), also without requiring a peer. See 15.4 for
  6999.      more discussion of this problem.
  7000.      If you override addNotify(), don't forget to call super.addNotify() in
  7001.      your overriding version.
  7002.  
  7003.  12. (Sect. 14) How can I force a reload a fresh version of an image into my
  7004.      applet? My image file is changed periodically, and I want the applet to
  7005.      go and retrieve it, not cache it.
  7006.  
  7007.      [*] You need to turn off caching for the URL.
  7008.  
  7009.      URL url = null;
  7010.      URLConnection con;
  7011.      try {
  7012.       url = new URL(getDocumentBase(),"image.jpg");
  7013.       con = url.openConnection();
  7014.       con.setUseCaches(false);
  7015.      } catch (MalformedURLException e1) {
  7016.             System.err.println(e1.getMessage());}
  7017.        catch (IOException e2) {
  7018.             System.err.println(e2.getMessage());}
  7019.  
  7020.      Note: Some programmers have reported that it caches anyway, even if
  7021.      they do this. That is a browser bug.
  7022.      One programmer reported that even after turning off caching and calling
  7023.      image.flush() before getImage(..), he was still seeing the same picture
  7024.      even though it had been changed on the server.
  7025.      He worked out a solution: access the image via a cgi script that
  7026.      returned a URL. This redirects the browser, and he put in an Expires:
  7027.      header as well to force the reload. Painful and laborious, but it got
  7028.      the result.
  7029.  
  7030.  13. (Sect. 14) How can I save an Image file to disk in JPG or GIF format?
  7031.  
  7032.      [*]
  7033.         o If you have an Image and you want a JPG in a file, download James
  7034.           Weeks's code from http://www.obrador.com/essentialjpeg/
  7035.         o Sean Breslin also wrote a program that compresses a Java Image
  7036.           into a JPEG file. http://www.afu.com/jpeg.txt
  7037.         o If you just want to convert some file, a non-Java solution is to
  7038.           use the standard IJG 'cjpeg' utility. It supports GIF, PPM, BMP,
  7039.           PNG and Targa input files.
  7040.         o If you have an Image and you want a GIF or PPM in a file, download
  7041.           Jef Poskanzer's abstract ImageEncoder class at
  7042.           http://www.acme.com/java/software/
  7043.      Also try the Java Image Management Interface (JIMI), which is free for
  7044.      non-commercial use. JIMI is a toolkit that lets your Java programs read
  7045.      and write many graphics file formats (PNG, JPG, BMP, GIF etc). JIMI is
  7046.      written in 100% Java, and best of all, it's a breeze to get started
  7047.      with. See http://www.activated.com/jimi.html
  7048.  
  7049.  14. (Sect. 14) What causes this problem:
  7050.  
  7051.      $ appletviewer m.html
  7052.      Premature end of JPEG file
  7053.      sun.awt.image.Im...Exception: JPEG datastream contains no image
  7054.      at sun.awt.image. ... .produceImage(JPEGImageDecoder.java:133)
  7055.      at sun.awt.image.Inpu...mageSource.doFetch(
  7056.                                    InputStreamImageSource.java:215)
  7057.      at sun.awt.image.ImageFetcher.run(ImageFetcher.java:98)
  7058.  
  7059.      [*] There's a known bug in early releases of the JDK which can cause
  7060.      the above failure when reading a JPEG across a slow connection. The
  7061.      failure only occurs if the JPEG contains a large application data block
  7062.      (APPn marker) - the problem is that the JPEG decoder is trying to skip
  7063.      over the APPn and failing if not all of the APPn has been received yet.
  7064.      The quoted error message is only one of several possible complaints,
  7065.      but they all stem from the same root.
  7066.      Photoshop is the most common source of JPEGs containing oversize APPn
  7067.      blocks. In particular, if you allow Photoshop 4 to save a thumbnail
  7068.      (preview) in a JPEG, the thumbnail plumps up Photoshop's private APPn
  7069.      marker to several K, which is usually enough to cause this problem.
  7070.      There are several possible workarounds:
  7071.         o Get a newer JDK - this problem is said to be fixed in 1.1. (If you
  7072.           are putting images up on the Web, this isn't much of a solution,
  7073.           because you can't assume visitors to your site have an up-to-date
  7074.           Java installation.)
  7075.         o When making JPEGs for Web use from Photoshop, make sure you have
  7076.           turned off the "save thumbnails" preference. (This is a good idea
  7077.           quite aside from bug workarounds, because the thumbnail is just a
  7078.           waste of download time as far as a Web browser is concerned.) You
  7079.           might still have a problem if you've got verbose comments or lots
  7080.           of paths being saved into the file, but 99% of the time, getting
  7081.           rid of the thumbnail will make Photoshop's APPn small enough to
  7082.           not trigger the Java bug.
  7083.         o Use a tool such as 'jpegtran' (from the Independent JPEG Group) to
  7084.           strip out the Photoshop APPn entirely without any loss of image
  7085.           quality. Recommended answer for the compulsive byte-trimmer.
  7086.         o (Last resort) Load and resave the image in a different image
  7087.           editor that won't insert any APPn or other overhead data. This
  7088.           implies a JPEG generational loss, so I don't recommend it if you
  7089.           are picky about image quality.
  7090.      Any large overhead marker will cause the same problem; 4K of comment
  7091.      text, say, in a COM marker. So Photoshop is not the only source of
  7092.      tickling this bug.
  7093.  
  7094.  15. (Sect. 14) How can I convert between GIF and JPEG formats?
  7095.  
  7096.      [*] In a word: don't.
  7097.      There's hardly any overlap between the set of images that JPEG works
  7098.      well on and the set that GIF works well on. Sometimes, with enough
  7099.      care, you can get an acceptable conversion...but most of the time
  7100.      GIF<->JPEG conversion will just turn your image to mush. It's better to
  7101.      pick the right format in the first place.
  7102.      Other sites:
  7103.         o If you're determined to convert formats anyway, try the GBM
  7104.           (Generalized Bitmap Module). The package is GNU licensed, in C and
  7105.           is very good. Find it at
  7106.           http://www.interalpha.net/customer/nyangau/
  7107.           GBM does a good job converting to JPEG, and 'lossiness' is
  7108.           adjustable to 0%. It also converts to/from about 20 other formats,
  7109.           does cropping, sizing, color mapping, gamma correction,
  7110.           halftoning, everything you could want. GBM source doesn't support
  7111.           JPEG directly, but utilizes JPEG source from IJG called jpeg-6a
  7112.           and found at
  7113.           ftp://sun2.urz.uni-heidelberg.de/pub/simtel/graphics/jpegsr6a.zip
  7114.         o For more info see the JPEG FAQ at
  7115.           http://www.faqs.org/faqs/jpeg-faq/
  7116.  
  7117.  16. (Sect. 14) If you have an InputStream (rather than a file) that
  7118.      contains an Image, how can you display it?
  7119.  
  7120.      [*] Use this method, and some adroit shuffling.
  7121.  
  7122.  
  7123.          Toolkit.getImage(URL url)
  7124.  
  7125.  
  7126.      Create a thread that pretends to be an http server. Make it listen to
  7127.      some port (8765 for example) for incoming requests. When the thread
  7128.      gets a request, it should simply whisk up the appropriate http headers
  7129.      and follow it by the InputStream. Thus the component that has the input
  7130.      stream and wants to do the getImage(url) can now invoke:
  7131.  
  7132.          Toolkit.getImage("localhost:8765/")
  7133.  
  7134.  
  7135.      The thread will act as a stream-to-url adapter, and send back the data
  7136.      It saves you from having to read 200K of JPEG data before you can begin
  7137.      drawing anything.
  7138.  
  7139.  17. (Sect. 14) How can I record sounds in Java?
  7140.  
  7141.      [*] The Java Media Framework will eventually support this, but it does
  7142.      not yet. JMF 1.0.1 only supports playback.
  7143.      JMF 1.0.1 is bundled with JDK 1.2, and available as a separate download
  7144.      for JDK 1.1 and Netscape Communicator 4 with Java 1.1.
  7145.      Other sites:
  7146.           In the meantime, there is a package for Win95/NT available at
  7147.           http://www.scrawl.com/store/. It supports 8, 16-bit, stereo, mono,
  7148.           11025, 22050, 44100 Hz record/play, load/save .WAV files. You
  7149.           could also interface to native code for your platform.
  7150.  
  7151.  18. (Sect. 14) Does Java have any built-in support for displaying HTML?
  7152.  
  7153.      [*] JDK 1.1 supports rendering HTML using the unbundled JFC 1.1 package
  7154.      known as Swing. The Swing package is bundled in JDK 1.2. It has an
  7155.      elementary (graphics, tables, text) HTML bean that is good enough for
  7156.      simple rendering (help files, email, etc).
  7157.      Other sites:
  7158.         o JavaBrowser http://www.ii.uib.no/~alexey/jb/index.html Free
  7159.           source, free for use under GNU LGPL licence, HTML 2.0 (sort of).
  7160.         o ICE Browser - Java Bean Component
  7161.           http://www.icesoft.no/ICEBrowser/ Free binaries for use in free
  7162.           applications. Commercial licensing available including source -
  7163.           flat fee licence. Thin HTML client! Lightweight! HTML 3.2
  7164.         o HotJava HTML Component - Java Bean Component
  7165.           http://www.javasoft.com/products/hotjava/bean/index.html $195 for
  7166.           private use binary licence. HTML 3.2
  7167.         o HTML browser (free source)
  7168.           http://barium.tn.tudelft.nl/people/gool/java/html/Html.html
  7169.         o Web Window Browser http://www.opencube.com/example_wwb.htm $139 -
  7170.           no sources.
  7171.         o jHelp ($20-650) http://w3.nai.net/~rvdi/jhelp/jhelp2/jhelp.html
  7172.           jHelp is a HTML browser component written in Java, HTML 2.0
  7173.  
  7174.  19. (Sect. 14) I loaded an Image file from a JPEG/GIF file using the
  7175.      Toolkit/Applet.createImage(URL/String) method, and (the height and
  7176.      width are -1 / it will not draw to the screen). What is wrong?
  7177.  
  7178.      [*] The behaviour of the AWT on creating images in this way is to do
  7179.      nothing at all.
  7180.      When the image is first drawn using Component.drawImage(), or its size
  7181.      is requested, the image begins to load in a different Thread.
  7182.      As the image loads, the ImageObserver specified in the
  7183.      drawImage()/getHeight() call is periodically notified of the loading
  7184.      status of the image, by calls to its imageUpdate() method.
  7185.      In the case of Component.drawImage() call, the default behavior of
  7186.      Component.imageUpdate() is to schedule *another* repaint() call when
  7187.      the image has fully loaded. This means that, in particular the
  7188.      following code will not work:
  7189.  
  7190.          class MyComponent extends Component {
  7191.            ...
  7192.            public void paint(Graphics g) {
  7193.              ImageFilter cropper=new CropImageFilter(0,0,16,16);
  7194.              Image cropped_image=createImage(new
  7195.              FilteredImageSource(image.getSource(),cropper));
  7196.              g.drawImage(image,10,400,this);        // this line works
  7197.               // this line doesn't -
  7198.              g.drawImage(cropped_image,400,15,this);
  7199.              }
  7200.            }
  7201.  
  7202.  
  7203.      The cropped_image will not be created in time to be painted, and when
  7204.      it is finally created, another call will be scheduled to paint, which
  7205.      will try to draw another one, etc.
  7206.      (Note also that creating objects like this in paint() methods is
  7207.      generally a very poor idea in Java, since they are called very
  7208.      frequently, and you will strongly offend the garbage collector.
  7209.      In order to get round this problem, you may i) add all such Images to a
  7210.      MediaTracker, and call the waitForAll() method. ii) implement your own
  7211.      ImageObserver interface, and wait for the imageUpdate() method to be
  7212.      called with the ALLBITS/FRAMEBITS value. i) is easier, but ii) is
  7213.      recommended, since there are reports of MediaTracker not working in
  7214.      some environments.
  7215.      Also in the FAQ:
  7216.         o See also Q13.12
  7217.         o See Q6.4 for examples of how to reuse objects.
  7218.  
  7219.  20. (Sect. 14) How can I record sound in an applet?
  7220.  
  7221.      [*] If you are using win95/nt, you could use SoundBite - Audio
  7222.      Recording in Applets. See http://www.scrawl.com/store/
  7223.      It provides easy access to audio data in arrays:
  7224.      short[] left, right;
  7225.  
  7226.  21. (Sect. 14) Does Java support PNG? Yes. PNG - Portable Network Graphics
  7227.      - provides a patent-free replacement for GIF and TIFF. If you save a
  7228.      GIF, don't forget to pay the royalty to Unisys - see Unisys's web page
  7229.      at http://www.unisys.com/LeadStory/lzwfaq.html. That patent is why GIFs
  7230.      are a poor choice for internet images.
  7231.  
  7232.      The PNG format is specified in RFCs 1950, 1951, and 2083, and is
  7233.      unencumbered by licenses or patents. See also the PNG-1.1 specification
  7234.      at ftp://swrinde.nde.swri.edu/pub/png/documents.
  7235.  
  7236.      The PNG format is supported by the Java Advanced Imaging API which is
  7237.      part of the 1.2 media APIs.
  7238.  
  7239.                        -------------------------------
  7240.  
  7241. 15. Networking and Distributed Objects
  7242.  
  7243.                                     RMI Issues
  7244.  
  7245.      Note that there is an RMI FAQ at
  7246.      http://java.sun.com/products/jdk/rmi/faq.html
  7247.  
  7248.   1. (Sect. 15) Should I use CORBA in preference to RMI? Or DCOM? Or what?
  7249.  
  7250.      [*] If your distributed programs are all in Java, then RMI provides a
  7251.      simpler mechanism that allows the transfer of code, pass-by-value of
  7252.      real Java objects, and automatic garbage collection of remote objects.
  7253.      If you need to connect to C++ (or other language) systems or you need
  7254.      CORBA-specific services, then CORBA is your choice.
  7255.      In July 1997, Sun announced that it was aligning RMI to work more
  7256.      closely with CORBA. Sun is simply adding an IIOP transport layer to RMI
  7257.      to support interoperability with CORBA. Java programs can then use RMI
  7258.      to access CORBA-based objects through IIOP, the OMG's CORBA-based
  7259.      protocol. This is very good news for those building heterogenous
  7260.      Enterprise systems, although it will take some additions to IIOP to
  7261.      support the pieces that RMI uses.
  7262.      In 1998 Microsoft spokespeople tried to promote DCOM by spreading
  7263.      misinformation that RMI is changing or being dropped. That is totally
  7264.      wrong. The RMI API continues unchanged in its current form. Using DCOM
  7265.      restricts your code to only ever run on Microsoft platforms using Intel
  7266.      hardware, and negates the "write once, run anywhere" Java philosophy.
  7267.      You would have to recompile your DCOM code to run it on other Microsoft
  7268.      platforms like Compaq's (formerly DEC's) alpha computer. Non-portable,
  7269.      single vendor code should be avoided. DCOM/DNA has limitations for use
  7270.      in the enterprise.
  7271.      Other sites:
  7272.           http://www.javaworld.com/javaworld/jw-10-1997/jw-10-corbajava.html
  7273.           has a good intro to CORBA in the Java world.
  7274.           http://www.objenv.com/cetus has a CORBA/RMI comparison.
  7275.  
  7276.   2. (Sect. 15) How do I do RMI into a different domain?"
  7277.  
  7278.      [*] Similar to the proxy answer in a section below; you must tell the
  7279.      program where to find the server. In this case start up the client with
  7280.      this commandline option: -Djava.rmi.server.hostname=hostname.domainname
  7281.  
  7282.   3. (Sect. 15) RMI seems to have stopped working for me in JDK 1.1. Why is
  7283.      this?
  7284.  
  7285.      [*] The rules for where the client looks for a stub class seem to have
  7286.      changed making it necessary to reset your class path on the client
  7287.      after starting the RMI registry. In particular, it looks like rmic was
  7288.      not updated to the new "don't need $CLASSPATH for current dir"
  7289.      convention as the compiler was. You are best off setting classpath
  7290.      explicitly.
  7291.      Other sites:
  7292.      There are several very good sources available from Sun which cover many
  7293.      simple and advanced RMI problems.
  7294.         o The documentation, of course:
  7295.           http://java.sun.com/products/jdk/1.1/docs/guide/rmi/index.html
  7296.         o Dedicated FAQs on RMI and Object Serialization
  7297.           http://java.sun.com/products/jdk/rmi/faq.html
  7298.         o Mailing list RMI-USERS@JAVASOFT.COM with archive at
  7299.           http://chatsubo.javasoft.com/email/rmi-users/ Visit the archive!
  7300.  
  7301.   4. (Sect. 15) After a number of RMI client to server connections (55 on my
  7302.      system), subsequent RMI clients trying to connect fail. Why?
  7303.  
  7304.      [*] You are hitting the default limit of 64 open file descriptors. Try
  7305.      increasing the limit in your OS.
  7306.      In addition there is currently a practical RMI connection limit imposed
  7307.      by the scalability of the VM and the performance of object
  7308.      serialization. This is addressed in JDK 1.2. The actual number of
  7309.      active clients you will be able to support will depend on the workload
  7310.      mix you have (i.e. the number of clients, how often they talk to the
  7311.      server, and how much work must be done per call).
  7312.  
  7313.   5. (Sect. 15) I'm using RMI on Win95, and the Naming.lookup() call is
  7314.      taking a long time, even for localhost. How do I fix it?
  7315.  
  7316.      [*] (See also the first answer in next section below, and note that
  7317.      this Windows workaround has never worked for some people). Try adding a
  7318.      definition for the machine in your "hosts" file. Typically, this file
  7319.      will be named c:\windows\hosts (if it doesn't exist, there should be a
  7320.      file called c:\windows\hosts.sam). The hosts file is searched by your
  7321.      TCP/IP stack before it resorts to DNS, so adding an entry in this file
  7322.      can speed up your lookups considerably. The hosts file is used to map
  7323.      IP addresses to symbolic addresses. To enter the name "localhost" with
  7324.      address 127.0.0.1 (the IP loopback address), enter the following line
  7325.      in your hosts file. 127.0.0.1 localhost
  7326.  
  7327.                                 Windows Networking
  7328.  
  7329.   6. (Sect. 15) Why does < Windows RMI/my java debugger/IDE/other> hang for
  7330.      a couple of minutes if my Windows PC is not dialed up to the Internet?
  7331.  
  7332.      [*] Java has networking support built in. When the Java program starts
  7333.      the Winsock DLL automatically gets loaded. The first thing this does is
  7334.      to try to resolve the fully qualified domain name for your machine
  7335.      under the name "localhost". If your system doesn't have this name
  7336.      mapped, it will try to query a nameserver on the internet, which is
  7337.      typically (on a PC) your dialup ISP. So it either prompts you to
  7338.      connect to the ISP, or waits till the attempt times out.
  7339.  
  7340.      Some people say you can avoid the Win95 problem by giving your system
  7341.      another way to resolve DNS names. This tip has never worked for me.
  7342.      Edit the hosts file for your system so that localhost and the full
  7343.      domain name are both mentioned. On Windows 95 systems the hosts file
  7344.      is: %windir%\HOSTS (for example, C:\WINDOWS\HOSTS). On Windows NT
  7345.      systems the hosts file is: %windir%\System32\DRIVERS\ETC\HOSTS (for
  7346.      example, C:\WINNT\System32\DRIVERS\ETC\HOSTS).
  7347.      One gotcha under Win95 is that if the last entry in the hosts file is
  7348.      not concluded with a carriage-return/line-feed then the hosts file will
  7349.      not be read at all. So if my system is called goober.best.com change
  7350.      the hosts file from
  7351.  
  7352.  
  7353.              127.0.0.1 localhost
  7354.  
  7355.  
  7356.      to
  7357.  
  7358.  
  7359.              127.0.0.1 goober.best.com localhost
  7360.  
  7361.  
  7362.      Showing more of the file:
  7363.  
  7364.           # Hosts file
  7365.           127.0.0.1       localhost
  7366.           129.146.77.177  goober
  7367.  
  7368.  
  7369.      Another alternative is to dial up with a PPP connection to your ISP
  7370.      whenever you want to run networking programs.
  7371.  
  7372.      Fundamentally the experience of some people has been that networking is
  7373.      not completely satisfactory on Windows95 using Winsock 1.1, and is
  7374.      subject to sporadic unexplained failures. You could try downloading
  7375.      Winsock 2.0. To get Winsock 2.0, you need to drag in all the other junk
  7376.      from Microsoft Windows Sockets 2.0 Software Development Kit. This free
  7377.      software can be downloaded from the following addresses:
  7378.      http://www.microsoft.com/win32dev/netwrk/winsock2/ws295sdk.html or
  7379.      ftp://ftp.microsoft.com/bussys/WinSock/winsock2/
  7380.  
  7381.      The patches needed to improve Win95 networking are already in Win98.
  7382.  
  7383.                              Other Networking Issues
  7384.  
  7385.   7. (Sect. 15) If I call the InetAddress.getByName() method with an
  7386.      IP-address-string argument, like "192.168.0.1", get an
  7387.      UnknownHostException on some platforms, but not others. Code like
  7388.  
  7389.      Socket sock = new Socket("155.152.5.1", 23);
  7390.  
  7391.      triggers the exception. Why?
  7392.  
  7393.      [*] This is a platform difference that arises out of different
  7394.      semantics in the underlying network libraries, and is [said to be, but
  7395.      subject to confirmation] fixed in JDK 1.1. On Solaris and Windows NT,
  7396.      the IP address string only works for IP addresses that have an
  7397.      associated hostname. On Linux and Windows 95, the IP address string
  7398.      works in all cases.
  7399.      When InetAddress is instantiated with an IP address, a reverse DNS
  7400.      lookup is done. If the IP address is not associated with a valid
  7401.      hostname, the instantiation will fail. This is part of anti
  7402.      DNS-spoofing, and in JDK 1.1 works because the reverse lookup will not
  7403.      occur until the hostname is asked for. So in JDK 1.1,
  7404.  
  7405.              InetAddress in = InetAddress.getByName("155.152.5.1");
  7406.  
  7407.  
  7408.      [Note: this info is still to be confirmed. Net gurus?]
  7409.      Other sites:
  7410.           Microsoft has several network-related patches at its site
  7411.           http://www.microsoft.com/
  7412.  
  7413.   8. (Sect. 15) I want to pass a class file to willing recipients who are
  7414.      using my applet. Any ideas how?
  7415.  
  7416.      [*] You could use a trick: put your .class file(s) in a .zip archive
  7417.      and use showDocument() on the URL. A person accessing this will get a
  7418.      dialog box put up asking them about saving the file to their local hard
  7419.      disk.
  7420.      Other sites:
  7421.           You can see this in action and try it out yourself at:
  7422.           http://www.best.com/~rmlynch/saveit.html
  7423.  
  7424.   9. (Sect. 15) How do I get a URLConnection to work through proxy
  7425.      firewalls? I.e. How do you get your Java application to do its web
  7426.      accesses through a proxy?
  7427.  
  7428.      [*] This is typically needed for any net access to another domain. Tell
  7429.      the run time system what you are trying to do, by using these
  7430.      commandline arguments when you start the program.
  7431.  
  7432.      java -DproxySet=true -DproxyHost=SOMEHOST -DproxyPort=SOMENUM code.java
  7433.  
  7434.      Note proxyPort is optional and it defaults to 80. Without this, you
  7435.      will see an exception like java.net.UnknownHostException or
  7436.      java.net.NoRouteToHostException
  7437.  
  7438.      The proxy settings work for both java.net.URLConnection, and for
  7439.      java.net.Sockets.
  7440.  
  7441.      Netscape's and IE's JVMs (at least in versions 4.x+) take the proxy
  7442.      settings for applets from the browser's proxy configuration. You can
  7443.      also do URL proxies in applications (not applets) with the following
  7444.      code
  7445.  
  7446.  
  7447.          // set up to use proxy
  7448.          System.getProperties().put("proxySet", "true");
  7449.          System.getProperties().put("proxyHost", "myproxy.server.name");
  7450.          System.getProperties().put("proxyPort", "80");
  7451.  
  7452.  
  7453.      But how do I know the name of the proxy server?
  7454.      This code just tells you how you can get a URL connection to the
  7455.      outside. Since it is your proxy server, you are expected to know the
  7456.      name of it. There isn't any code that you can write that will allow
  7457.      arbitrary URL connections to be initiated from outside the firewall.
  7458.      Think about it! If there were, the firewall would not be doing its job.
  7459.  
  7460.      Also note there are corresponding socksProxyPort and socksProxyHost for
  7461.      when socks is used instead of proxy. The default socks port is 1080.
  7462.  
  7463.  10. (Sect. 15) What is "swizzle", as in "Swizzle this object?"
  7464.  
  7465.      [*] It means serialize. To swizzle an object is to recursively
  7466.      serialize or flatten composed objects.
  7467.  
  7468.  11. (Sect. 15) I have been using the Serializing capabilities in 1.1 to
  7469.      save some objects to disk. I added a new field to one of my objects
  7470.      that get serialized and now deserializing my old data no longer works.
  7471.      I get this exception:
  7472.  
  7473.  
  7474.      java.io.InvalidClassException: MacroData; Local class not compatible
  7475.  
  7476.  
  7477.      [*] You need to add a declaration such as
  7478.  
  7479.  
  7480.          static final long serialVersionUID = 4021215565287364875L;
  7481.  
  7482.  
  7483.      in the modified class. The actual value of this long is supplied by the
  7484.      "serialver" utilitity suppied with the JDK. Any versions of a class
  7485.      other than the first version require this static to be defined in the
  7486.      class. This is how versioning is achieved.
  7487.  
  7488.  12. (Sect. 15) My socket code looks good, but is broken!
  7489.  
  7490.      [*] When using sockets you typically open both inward and outward
  7491.      streams. A TCP connection is full duplex, but either the send or
  7492.      receive side may be closed independently. By default, the remote end
  7493.      will take the close as indicating that the connection has simply been
  7494.      closed, and will close its end as well. Check whether this is happening
  7495.      for you, by adding the matched pair. Use tcpdump to check this.
  7496.  
  7497.  13. (Sect. 15) How do I map between IP address and hostname?
  7498.  
  7499.      [*] In Java 1.1 (earlier releases were buggy) use:
  7500.  
  7501.  
  7502.          String host = InetAddress.getByName("211.10.2.119").getHostName();
  7503.  
  7504.  
  7505.  14. (Sect. 15) How do I embed an anchor in a URL? Just putting it as part
  7506.      of the string in the constructor doesn't work.
  7507.  
  7508.      [*] Like this:
  7509.  
  7510.  
  7511.          URL url = new URL("http://www.my_domain.com/my_page.html");
  7512.          URL anchor = new URL(url, "#section2");
  7513.          this.getAppletContext().showDocument(anchor);
  7514.  
  7515.  
  7516.  15. (Sect. 15) How do I POST to a CGI script from an applet?
  7517.  
  7518.      [*] Let's start by noting that this is more troublesome than it might
  7519.      seem at first, and that GET is preferred. For an untrusted applet, the
  7520.      CGI script can only be on the server that served the applet. POSTing to
  7521.      the server involves sending key/value pairs, not just a message. Also
  7522.      values must be encoded. To send "words to the server" you might try:
  7523.  
  7524.  
  7525.      StringBuffer sb = new StringBuffer();
  7526.      String str="words to the server";
  7527.  
  7528.      sb.append("message=");
  7529.      sb.append(java.net.URLEncoder.encode(str));
  7530.      URLConnection cn = url.openConnection();
  7531.  
  7532.      // set properties
  7533.      cn.setDoOutput(true);
  7534.      cn.setUseCaches(false);
  7535.      cn.setAllowUserInteraction(false);
  7536.      cn.setRequestProperty("content-type","application/x-www-form-urlencoded");
  7537.  
  7538.      // send parameters
  7539.      PrintWriter out = new PrintWriter(cn.getOutputStream());
  7540.      out.print(sb.toString());
  7541.      out.close();
  7542.  
  7543.      // read stuff
  7544.  
  7545.      BufferedReader in = new BufferedReader(
  7546.                            new InputStreamReader(
  7547.                              cn.getInputStream()));
  7548.  
  7549.      sb = new StringBuffer();
  7550.      String inputLine;
  7551.  
  7552.      while ((inputLine = in.readLine()) != null){
  7553.          sb.append(inputLine);
  7554.          sb.append("\n");
  7555.  
  7556.      }
  7557.      in.close();
  7558.  
  7559.  
  7560.          uresp = new URL(getDocumentBase(),"respond.html");
  7561.          getAppletContext().showDocument(uresp); }
  7562.  
  7563.  
  7564.      The CGI has to write its output to respond.html so that it can be
  7565.      displayed by the browser. But it may still fail, because respond.html
  7566.      could be overwritten by a subsequent request to the same CGI before the
  7567.      results of the first POST are read back.
  7568.      To get an acceptable solution takes quite a lot of effort. In general
  7569.      you should prefer GET to POST for CGI access from Java. As it says on
  7570.      the Javaworld page, the answers to the question are really: you can't,
  7571.      don't POST (use GET), use a bean, or cheat.
  7572.  
  7573.      Note, if you request a URL via the URLConnection/HttpURLConnection, the
  7574.      server sets the content type, and your applet can use
  7575.      URLConnection.getContentType() to get the type. Alternatively, use
  7576.      setRequestProperty to set it, like this:
  7577.  
  7578.  
  7579.          url = new URL(cgiUrl);
  7580.          urlc = url.openConnection();
  7581.          urlc.setRequestProperty(
  7582.                         "Content-type",
  7583.                         "application/x-www-form-urlencoded");
  7584.  
  7585.  
  7586.      Other sites:
  7587.           There's a pretty good explanation at
  7588.           http://www.javaworld.com/javaworld/javatips/jw-javatip41.html
  7589.  
  7590.      See also the Marty Hall book Core Web Programming (Prentice Hall ISBN:
  7591.      0-13-625666-X). It has comprehensive coverage of writing Java programs
  7592.      that interface to CGI scripts. Better still, use servlets, write
  7593.      everything in Java, and discard your CGI code.
  7594.  
  7595.  16. (Sect. 15) How can I write CGI programs in Java?
  7596.  
  7597.      [*] CGI (the Common Gateway Interface for web servers) is an API for
  7598.      writing programs that use the web as its user interface. By far, the
  7599.      most popular language for this task is Perl, because of its powerful
  7600.      text handling capabilities, and excellent resources available for
  7601.      making the jobs of CGI programmers easier. CGI programs can be written
  7602.      in any language, including Java.
  7603.      Unfortunately, the interface between the web server and the CGI program
  7604.      uses environment variables extensively. Use of environment variables
  7605.      has always been deprecated in Java, because of portability issues (not
  7606.      all systems have environment variables). The way to get around this is
  7607.      to write a "wrapper" for the Java program in a language that supports
  7608.      environment variables, and can then invoke the Java program with the
  7609.      appropriate environment data passed in as Java properties.
  7610.      Because the Java runtime environment is not a lightweight process, it
  7611.      might take a moment for the CGI program to get started before anything
  7612.      happens. This is particularly true on operating systems, like NT, that
  7613.      have a large overhead to spawning new processes.
  7614.      In preference to using Java for CGI on the server, you might consider
  7615.      using the Java servlet API in Netscape's Enterprise Server. This allows
  7616.      you to develop server-side programs in Java without suffering the same
  7617.      performance restrictions and other limitations of the CGI API.
  7618.      Other sites:
  7619.      See http://search.netscape.com/comprod/server_central/
  7620.      query/eval_guide/enterprise/advantage.html for more details.
  7621.  
  7622.  17. (Sect. 15) How can I write the "ping" program in Java?
  7623.  
  7624.      [*] You can't do it directly. Quoting from the Java Networking FAQ,
  7625.  
  7626.           Ping requires ICMP packets. These packets can only be created
  7627.           via a socket of the SOCK_RAW type. Currently, Java only
  7628.           allows SOCK_STREAM (TCP) and SOCK_DGRAM (UDP) sockets. It
  7629.           seems unlikely that this will be added very soon, since many
  7630.           Unix versions only allow SOCK_RAW sockets to be created by
  7631.           root, and winsock does not address ICMP packets (win32
  7632.           includes an unsupported and undocumented ICMP.DLL).
  7633.  
  7634.      You could write a program that handshakes with a remote system, to
  7635.      simulate ping, or you could use native code for the raw socket. Other
  7636.      sites:
  7637.           You can find the Java Networking FAQ at
  7638.           http://www.io.com/~maus/JavaNetworkingFAQ.html
  7639.  
  7640.           There is an additional Java Networking FAQ (which is being
  7641.           modified and reposted regularly) at
  7642.           http://www.davidreilly.com/java/java_network_programming/
  7643.  
  7644.  18. (Sect. 15) Why, when I make a call to DatagramPacket.getlength() does
  7645.      it returns the wrong size?
  7646.  
  7647.      [*] You are probably reusing a Datagram packet, and it has no way to
  7648.      grow its buffer if a longer packet comes in. Take care of it by calling
  7649.      setLength(max) before reuse.
  7650.  
  7651.      Failing to do this is a very common mistake.
  7652.  
  7653.  19. (Sect. 15) Why do my networking programs freeze on the Mac?
  7654.  
  7655.      [*] You shouldn't println to a socket. This is the subject of Apple
  7656.      Technical Note 1157 at
  7657.      http://developer.apple.com/technotes/tn/tn1157.html
  7658.      The problem is that many socket protocols expect CR+LF to terminate a
  7659.      string, but println delivers a platform-specific EOL mark. On the Mac,
  7660.      it is just CR. Therefore the server hangs waiting for the Mac to send a
  7661.      LF. It never does. But the program works fine on platforms that send
  7662.      CR+LF.
  7663.  
  7664.  20. (Sect. 15) How do I "timeout" a socket read, as the "select" function
  7665.      in Unix does?
  7666.  
  7667.      [*] There are two timeouts at issue here.
  7668.      Use the ServerSocket.setSoTimeout(int millis) for timing out your
  7669.      'accept()' calls.
  7670.  
  7671.      For a select() like mechanism, you can poll InputStreams of your
  7672.      connections for available() > 0
  7673.  
  7674.      URLConnection doesn't have a method for this, but you can do it by
  7675.      using multiple threads. Create a timer thread that would just track
  7676.      time and close the connection after your specified timeout period.
  7677.      Check the URLConnection to see if it's got any data flowing through it
  7678.      (calling URLConnection.connected() is probably a sufficient test). The
  7679.      URLConnection should be in a separate thread.
  7680.  
  7681.                        -------------------------------
  7682.  
  7683. 16. Security
  7684.  
  7685.   1. (Sect. 16) What is a "trusted applet"?
  7686.  
  7687.      [*] JDK 1.1 introduced the notion of a "trusted applet" which is one
  7688.      that has been cryptographically signed to guarantee its origin and make
  7689.      it tamper-resistant. Trusted applets can be granted more system access
  7690.      privileges than untrusted applets.
  7691.      You preconfigure your browser with a list of whose X.509 certificate
  7692.      you trust, and then applets arrive with X.509's attesting to their
  7693.      keys. It's easier than it sounds.
  7694.  
  7695.   2. (Sect. 16) What is the story with Java and viruses? What is the
  7696.      blackwidow virus?
  7697.  
  7698.      [*] Java was designed with security in mind. The security features make
  7699.      it very difficult, probably impossible, to attach a virus (self-copying
  7700.      code) to a Java applet. There has never been a Java virus carried from
  7701.      system to system by applets.
  7702.      There has been mention of a "Java virus" called "BlackWidow" in the
  7703.      media (it was mentioned in Unigram in late 1996, and obliquely on the
  7704.      RISKS newsletter in February 1997). A request to the editor of Unigram
  7705.      for more information brought the answer that there was no more
  7706.      information, it was just a report of a rumor. As far as is known, this
  7707.      story exists only as rumors reported on by the press. There is no
  7708.      actual Java virus or blackwidow virus (there was a legitimate
  7709.      commercial product of that name, since renamed).
  7710.      In spring 1998 there were press reports of a "Java applet" called White
  7711.      Ghost. It turns out that it relies on security flaws in ActiveX, and
  7712.      the only susceptible systems are Microsoft's Active Desktop. If anyone
  7713.      has a URL for a copy of this code, and an analysis of it, please
  7714.      contact the FAQ author.
  7715.  
  7716.      In August 1998, Symantec had some information about a Java program
  7717.      (application) that could append itself to some other Java program. They
  7718.      termed it "Strange Brew". That is just normal file processing, no
  7719.      different to a program written in C, C++, Fortran, COBOL, etc. What
  7720.      makes PC viruses dangerous is when they have a hidden means of
  7721.      travelling between places, such as being attached to code that is
  7722.      automatically executed, like boot sector code, or Word macro
  7723.      initialization files. No one has yet produced a virus that does this in
  7724.      Java.
  7725.  
  7726.      In March 1999, reports surfaced of a virus called BeanHive. Again this
  7727.      was not Java-related, but relied on the browser user explicitly
  7728.      accepting an unknown certificate as trusted when prompted. If the user
  7729.      allowed that, then any code from that source will be uploaded and run
  7730.      without further input from the user. Don't remove security for
  7731.      untrusted code simply because it asks for it, is the lesson here.
  7732.      If anyone has more concrete information about a virus that can attack a
  7733.      Java applet (again, this is thought to be impossible), please contact
  7734.      the FAQ author.
  7735.  
  7736.   3. (Sect. 16) Why do I get the warning string "Unsigned Java Applet
  7737.      Window" at the bottom of popup windows in my applets?
  7738.  
  7739.      [*] This is a security feature, to make certain that users can always
  7740.      tell that a window asking for their password and credit card details
  7741.      (or whatever) is from an applet. There should be no way for an
  7742.      untrusted applet to work around this message.
  7743.      Also in the FAQ:
  7744.      See also the answer to Q12.7.
  7745.  
  7746.   4. (Sect. 16) Where can I find information on signing applets?
  7747.  
  7748.      [*] Please take a look at the "Code Signing for Java Applets" page at
  7749.      http://www.suitable.com/Doc_CodeSigning.shtml. The page explains how to
  7750.      sign your Java applet so that it can be used in both
  7751.      Navigator/Communicator and Internet Explorer.
  7752.  
  7753.   5. (Sect. 16) Where can I find crypto libraries for Java?
  7754.  
  7755.      [*] Cryptographic libraries are not part of the Java release because US
  7756.      Government policy classifies strong cryptography under the same rules
  7757.      as munitions. Its export is regulated under the International Traffic
  7758.      in Arms Regulations. Many people regard this as a Kafka-esque (and
  7759.      futile) attempt to stem the use of cryptography inside the US.
  7760.      Other sites:
  7761.         o The comprehensive and free "Cryptix" crypto library written in
  7762.           Java is at:
  7763.           http://www.cryptix.org
  7764.           See also http://www.hi.is/~logir/logi.crypto/
  7765.         o Another free crypto library for Java is at:
  7766.           http://www.acme.com/java/software/Package-Acme.Crypto.html
  7767.           It includes Blowfish, CRC16, CRC32, DES, DES3, IDEA, RC4, ROT13
  7768.           (can they really call that "crypto"?), and more.
  7769.         o Another pure Java Cryptography toolkit is at
  7770.           http://www.freestylesoft.com/products/crypto/avalanche.html (free
  7771.           for personal use).
  7772.         o One commercial Java encryption source (from Ireland) is:
  7773.           http://www.baltimore.ie/jcrypto.htm
  7774.         o A complete crypto API for Java (with HTML documentation) at:
  7775.           http://www.geocities.com/SiliconValley/Heights/8298
  7776.           The library provides comprehensive and complete range of crypto
  7777.           library and functions covering DES, 3DES, IDEA, Blowfish ...and
  7778.           RSA, DH, DSA and PGP access to Java programmers. The crypto
  7779.           functions are based on the C cryptlib, by Peter Gutmann. It would
  7780.           be illegal to export this under current US government rules, but
  7781.           the author of the code is outside the US, and not subject to US
  7782.           export regulations. Download it today before it becomes illegal.
  7783.         o Some Java crypto available with source under GPL is at
  7784.           http://www.aba.net.au/solutions/crypto/jce.html
  7785.           http://www.geocities.com/SiliconValley/1394/
  7786.         o Also, data about Sun's Java Cryptography Extension (JCE) is
  7787.           available at:
  7788.           http://developer.java.sun.com/developer/earlyAccess/jdk12/jce.html
  7789.  
  7790.           (This may not be exported outside the USA and Canada).
  7791.         o An actual port of PGP v2.6.3i to Java is at:
  7792.           http://tassun.math.nsc.ru
  7793.         o A list of free crypto libraries, not necessarily in Java, and of
  7794.           course the FBI will be all over you like hair on an ape if you try
  7795.           to export any of these, is at:
  7796.           http://www.homeport.org/~adam/crypto/
  7797.  
  7798.   6. (Sect. 16) How do I find out what these terms mean?
  7799.  
  7800.      [*] Read Bruce Schneier's excellent book "Applied Cryptography 2nd Ed."
  7801.      for more info on what these terms mean. Read David Kahn's excellent
  7802.      (and exhaustive) book "The Codebreakers" for more info on the history
  7803.      and background of encryption.
  7804.  
  7805.   7. (Sect. 16) Where is Javasoft's Security FAQ?
  7806.  
  7807.      [*] Javasoft's security FAQ can be found at:
  7808.      http://java.sun.com/sfaq/index.html
  7809.      Other sites:
  7810.           http://java.sun.com/products/jdk/1.1/docs/guide/security/
  7811.  
  7812.   8. (Sect. 16) Where is that online book on Java Security?
  7813.  
  7814.      [*] Gary McGraw and Ed Felten's book Securing Java can be found on the
  7815.      web at
  7816.      http://www.securingjava.com/
  7817.  
  7818.                        -------------------------------
  7819.  
  7820. 17. For C and C++ Afficionados
  7821.  
  7822.   1. (Sect. 17) How do I translate C/C++ into Java or vice-versa?
  7823.  
  7824.      [*] In general it is not simple to translate C/C++ into Java, as Java
  7825.      lacks the arbitrary pointer arithmetic of those languages. If your C
  7826.      code does not use pointer arithmetic, automatic translation gets a lot
  7827.      simpler. Try these URLs:
  7828.           http://www.ist.co.uk (search for X-Designer 4.6: Java edition).
  7829.           http://members.aol.com/laffra/c2j.html
  7830.           http://www.ilog.com/
  7831.  
  7832.      Going the other way there are currently three freely-available tools to
  7833.      translate Java into C. It seems that these have been done for hacking
  7834.      value, rather than practical purposes.
  7835.         o j2c from Japan,
  7836.                http://www.webcity.co.jp/info/andoh/java/j2c.html
  7837.         o Toba from the Sumatra research project, translates 1.0.2 .class
  7838.           files into .c source code
  7839.                http://www.cs.arizona.edu/sumatra/toba
  7840.         o JCC from Nik Shaylor.
  7841.                http://www.geocities.com/CapeCanaveral/Hangar/4040/
  7842.  
  7843.      None of them support the AWT yet, and both j2c and JCC have additional
  7844.      restrictions.
  7845.  
  7846.      There's a product to convert Visual Basic to Java. Details at
  7847.           http://www.blackdirt.com and
  7848.           http://www.javadelphi.com (also a Delphi-to-Java source converter)
  7849.           and
  7850.           http://www.tvobjects.com
  7851.      There's a product to translate COBOL source to Java source, see
  7852.      http://www.Synkronix.com/
  7853.  
  7854.      This program dumps info about the class file:
  7855.           http://www.professionals.com/~cmcmanis/java/dump/index.html
  7856.  
  7857.      Chuck McManis was one of Sun's original Java implementors.
  7858.  
  7859.   2. (Sect. 17) How are finalizers different from C++ destructors?
  7860.  
  7861.      [*] Java objects are not explicitly deleted and do not have
  7862.      destructors. Instead they are implicitly garbage collected when the JVM
  7863.      realizes your program can no longer access them. Typically this
  7864.      technology is _not_ based on reference counting and _will_ cope with
  7865.      circular references.
  7866.  
  7867.      Every object has a routine called finalize() which will be called
  7868.      before the object is collected. This is Java's nearest equivalent to
  7869.      C++'s destructor. However, it is not a good idea to rely on
  7870.      finalization for the timely freeing of resources.
  7871.  
  7872.      This is because garbage collection and hence finalization may be
  7873.      arbitrarily delayed, and may never happen at all if the program
  7874.      terminates before it runs out of memory. You should instead provide
  7875.      your objects with methods similar to Graphics.dispose() to free
  7876.      resources, and call the dispose() method explicitly when you have
  7877.      finished using them - typically within the "finally" clause of a
  7878.      "try/catch" block. You may then call your dispose() method from within
  7879.      your finalize() method as a last-ditch attempt to free the resource if
  7880.      someone forgets.
  7881.  
  7882.      Alas, all this means the C++ idiom of "object construction is resource
  7883.      aquisition" does not translate well to Java. However, note that 90% of
  7884.      destructors in C++ are there to free memory, and the GC means you don't
  7885.      need to do that in Java. As well as fixing an important source of bugs,
  7886.      the GC is essential to Java's security model; without it you could
  7887.      forge object references by preserving the reference after the object
  7888.      has been deleted.
  7889.  
  7890.      If your program appears to be crashing due to running out of some
  7891.      system resource (like File, Window or Graphics handles), it probably
  7892.      because the system is running out of handles before it has run out of
  7893.      memory. Check that you have called the dispose() method (or equivalent)
  7894.      on every object that uses system resources. You can help the GC a
  7895.      little bit more by explicitly NULLing out references that you've
  7896.      finished with.
  7897.  
  7898.   3. (Sect. 17) What's the Java equivalent of sizeof()?
  7899.  
  7900.      [*] There isn't one. sizeof() in C and C++ is used in three main
  7901.      places:
  7902.        1. To check on the size of a primitive type. In Java, the sizes of
  7903.           primitive types are fixed in the language specification (a short
  7904.           is _always_ 16 bits; an int is _always_ 32 bits, etc), so this is
  7905.           no longer necessary.
  7906.        2. In memory allocation (i.e. malloc (32 * (sizeof(int));) In Java
  7907.           you always allocate a specific type of object, rather than a block
  7908.           of raw memory that you will fill as you like. The system always
  7909.           knows the size of the kind of objects you are allocating. So
  7910.           sizeof is not needed.
  7911.        3. In pointer arithmetic (i.e. p += sizeof (int)) Pointer arithmetic
  7912.           of this type is not allowed in Java, so this isn't necessary,
  7913.           either.
  7914.  
  7915.      For all these reasons, there is no need for a Java sizeof() operator.
  7916.      by having the object serialize itself to a ByteArrayOutputStream, and
  7917.      looking at the bytearray.length.
  7918.  
  7919.      That won't work because a lot of additional data is written when an
  7920.      object is serialized. The additional data includes a description of the
  7921.      class, any objects referenced by the serialized object, null references
  7922.      (written as a single byte), etc. If you write another instance of the
  7923.      same class, the amount of data written can differ dramatically. And if
  7924.      you serialize the same object again, it isn't written at all -- even if
  7925.      its data fields have changed! Instead, a one byte token and a four byte
  7926.      "sequence number" that refer to the first writing are output. Using
  7927.      Object Serialization to determine the size of an object does not
  7928.      (except by coincidence) give the right answer.
  7929.  
  7930.   4. (Sect. 17) Does Java have the equivalent of "const" arguments in C and
  7931.      C++?
  7932.  
  7933.      [*] Java 1.1 adds the ability to use the "final" keyword to make
  7934.      arguments constant. When used to qualify a reference type, however,
  7935.      this keyword indicates that the reference is constant, not that the
  7936.      object or array referred to is constant. For example, the following
  7937.      Java code:
  7938.  
  7939.           void foo(final MyClass c, final int a[]) {
  7940.               c.field = 7; // allowed
  7941.               a[0] = 7; // allowed
  7942.               c = new MyClass(); // final means this is NOT allowed
  7943.               a = new int[13]; // final means this is NOT allowed
  7944.           }
  7945.  
  7946.      is roughly equivalent to the following C/C++ code:
  7947.  
  7948.           void foo(MyClass * const c, int * const a) {
  7949.               c->field = 7; // allowed
  7950.               a[0] = 7; // allowed
  7951.               c = new MyClass(); // const means this is NOT allowed
  7952.               a = new int[13]; // const means this is NOT allowed
  7953.           }
  7954.  
  7955.      Java does not have any equivalent to the following C/C++ function
  7956.      declarations:
  7957.  
  7958.           void foo(const MyClass *c); // a pointer to a const class
  7959.           void foo(const int *a); // a pointer to a const int
  7960.           void foo(const int a[]); // a pointer to an array of const ints
  7961.  
  7962.   5. (Sect. 17) Are there any hacks around this?
  7963.  
  7964.      [*] Certainly! There are always hacks around stuff. One way of
  7965.      enforcing constant values is to have two interfaces, a constant one and
  7966.      a non-constant one, e.g.
  7967.  
  7968.           public interface ConstFoo {
  7969.              int getValue();
  7970.           }
  7971.  
  7972.           public interface Foo extends ConstFoo {
  7973.               int getValue();
  7974.               void setValue(int i);
  7975.           }
  7976.  
  7977.      Then when you want to receive a parameter that cannot be modified you
  7978.      have:
  7979.  
  7980.           void noChange(ConstFoo foo);
  7981.  
  7982.  
  7983.      For a parameter that can be modified
  7984.  
  7985.           void change(Foo foo);
  7986.  
  7987.  
  7988.   6. (Sect. 17) How can I write C/C++ style assertions in Java?
  7989.  
  7990.      [*] The two classes shown below provide an assertion facility in Java.
  7991.      Set Assert.enabled to true to enable the assertions, and to false to
  7992.      disable assertions in production code. The AssertionException is not
  7993.      meant to be caught--instead, let it print a trace. Since the exception
  7994.      is not meant to be caught, we just extend Error instead of
  7995.      RuntimeException. As with RuntimeException, a method does not need to
  7996.      declare that it throws Error. In addition programmers are less likely
  7997.      to write "catch(Error) ..." than "catch(RuntimeException)".
  7998.  
  7999.      With a good optimizing compiler there will be no run time overhead for
  8000.      many uses of these assertions when Assert.enabled is set to false.
  8001.      However, if the condition in the assertion may have side effects, the
  8002.      condition code cannot be optimized away. For example, in the assertion
  8003.  
  8004.           Assert.assert(size() <= maxSize, "Maximum size exceeded");
  8005.  
  8006.      the call to size() cannot be optimized away unless the compiler can see
  8007.      that the call has no side effects. C and C++ use the preprocessor to
  8008.      guarantee that assertions will never cause overhead in production code.
  8009.      Without a preprocessor, it seems the best we can do in Java is to write
  8010.  
  8011.           Assert.assert(Assert.enabled && size() <= maxSize, "Too big");
  8012.  
  8013.           Alternatively, use
  8014.  
  8015.               if (Assert.enabled)
  8016.                   Assert.assert( size() <= maxSize, "Too big" );
  8017.  
  8018.      In this case, when Assert.enabled is false, the method call can always
  8019.      be optimized away totally, even if it has side effects. The relevant
  8020.      sections of the JLS are Section 13.4.8, final Fields and Constants and
  8021.      Section 14.19, Unreachable Statements. 13.4.8 requires that primitive
  8022.      constants ("a field that is static, final, and initialized with a
  8023.      compile-time constant expression") be inlined. So everywhere
  8024.      Assert.enabled is refered it is replaced at compile time with its
  8025.      value. Writing:
  8026.  
  8027.            if (Assert.enabled) Assert.assert(size() <= maxSize, "Too big");
  8028.  
  8029.      is exactly the same as writing:
  8030.  
  8031.            if (false) Assert.assert(size() <= maxSize, "Too big");
  8032.  
  8033.      ... assuming Assert.enabled is false at compile time. Section 14.19
  8034.      discusses compiling away such dead code. To sum up: the inlining of the
  8035.      primitive constant is required by the spec. The subsequent optimization
  8036.      of not generating code masked by (what turns into) an "if (false) ..."
  8037.      is not required but is implemented by many existing Java compilers.
  8038.  
  8039.           public class AssertionException extends Error {
  8040.               public AssertionException(String s) {
  8041.                  super(s);
  8042.               }
  8043.           }
  8044.  
  8045.           public final class Assert {
  8046.               public static final boolean enabled = true;
  8047.               public static final void assert(boolean b, String s) {
  8048.                   if (enabled && !b)
  8049.                       throw new AssertionException(s);
  8050.               }
  8051.           }
  8052.  
  8053.   7. (Sect. 17) How do I do stuff like scanf and sscanf in C/C++? And how do
  8054.      I do stuff like sprintf, e.g.
  8055.  
  8056.      float x = 12345.6789;
  8057.      printf("%6.3f/n", x);
  8058.  
  8059.      [*] You can break a string like "5 loaves 2 fishes" into its parts by
  8060.      using java.util.StringTokenizer. This is the Java equivalent of
  8061.      sscanf().
  8062.  
  8063.      StreamTokenizer does a similar thing on a file or any stream (i.e, what
  8064.      scanf() and fscanf() do in C).
  8065.  
  8066.      To do formatted character output, create a format string, and then use
  8067.      that to format your binary value, e.g.
  8068.  
  8069.           import java.text.*;
  8070.  
  8071.           float fi = 1234.56789F;
  8072.           DecimalFormat mydf = new DecimalFormat( "###0.000" );
  8073.           mydf.setMinimumIntegerDigits(3);  // for example
  8074.           System.out.println( mydf.format(fi) );
  8075.  
  8076.      gives:
  8077.           1234.567
  8078.  
  8079.      If you want to see a float print out as "0.0000001" instead of "1E-7",
  8080.      use:
  8081.  
  8082.      java.text.DecimalFormat myFmt = new
  8083.          java.text.DecimalFormat("#,###,###,###.############");
  8084.      System.out.println(myFmt.format(myFloat));
  8085.  
  8086.      There are lots of different characters you can feed to the
  8087.      DecimalFormat constructor, not just "0" and "#". See
  8088.      $JAVAHOME/src/java/text/DecimalFormat.java source for details.
  8089.  
  8090.      The always excellent Acme site has an sprintf() package written in Java
  8091.      See http://www.acme.com.
  8092.  
  8093.   8. (Sect. 17) What is the Java equivalent of C++'s "friend"?
  8094.  
  8095.      [*] The keyword "friend" in C++ is a hack to allow a piece of code to
  8096.      access the private member declarations of another class. In Java, you
  8097.      would do this by labelling, not the friend, but the private members.
  8098.      Instead of making them private, make them either protected or package
  8099.      (no keyword) or public.
  8100.  
  8101.      The four different Java protection levels are: private, package,
  8102.      protected, and public.
  8103.         o private members can only be accessed by the containing class and
  8104.           internal classes.
  8105.         o package (specified by omitting other keywords) is the default
  8106.           level of protection; members are accessible from any class within
  8107.           the package of the containing class.
  8108.         o protected is package-level-access plus access to sub-classes of
  8109.           the containing class. So "protected" is less protected than the
  8110.           default.
  8111.         o public fields in public classes are accessible from all classes.
  8112.  
  8113.   9. (Sect. 17) Does anything like the C++ Standard Template Library exist
  8114.      for Java?
  8115.  
  8116.      [*] Yes, only it's better and simpler to use in Java. It's called the
  8117.      Java Generic Library. This library (JGL) is freely downloadable from
  8118.      http://www.objectspace.com/
  8119.  
  8120.      It includes about a dozen nice data structures (including sets and
  8121.      bags) and algorithms like unions, searching, and sorting.
  8122.  
  8123.      It has over 100,000 users and 11 OEM distributors. [Some Java vendors
  8124.      are bundling it with their next release]
  8125.  
  8126.  10. (Sect. 17) What happens to post-increment when an exception is thrown?
  8127.  
  8128.      [*] If you have the code:
  8129.  
  8130.          array[i++] = foo();
  8131.  
  8132.      and foo() throws an exception, i will be incremented anyway. This can
  8133.      cause problems if sometimes foo() throws an exception and you don't
  8134.      want i incremented in cases when it does.
  8135.  
  8136.      This is a consequence of JLS 15.25.1 and 15.6.1 "the left-hand operand
  8137.      of a binary operator appears to be fully evaluated before any part of
  8138.      the right-hand operand is evaluated." (assignment is taken as a binary
  8139.      operator). Note that this is not how C++ behaves.
  8140.  
  8141.                        -------------------------------
  8142.  
  8143. 18. Java Idioms
  8144.  
  8145.      See also the list of Java Design Patterns at
  8146.      http://c2.com/cgi/wiki?JavaIdioms
  8147.  
  8148.   1. (Sect. 18) What are the naming conventions in Java?
  8149.  
  8150.      [*] The naming conventions are straightforward:
  8151.         o Package names are guaranteed uniqueness by using the Internet
  8152.           domain name in reverse order: com.javasoft.jag - the "com" or
  8153.           "edu" (etc.) part used to be in upper case, but now lower case is
  8154.           the recommendation.
  8155.         o Class and interface names are descriptive nouns, with the first
  8156.           letter of each word capitalized: PolarCoords. Interfaces are often
  8157.           called "something-able", e.g. "Observable", "Runnable",
  8158.           "Sortable".
  8159.         o Object and data (field) names are nouns/noun phrases, with the
  8160.           first letter lowercase, and the first letter of subsequent words
  8161.           capitalized: currentLimit.
  8162.         o Method names are verbs/verb phrases, with the first letter
  8163.           lowercase, and the first letter of subsequent words capitalized:
  8164.           calculateCurrentLimit.
  8165.         o Constant (final) names are in caps: UPPER_LIMIT.
  8166.      Other sites:
  8167.         o Check out the section "Naming Conventions" in the language
  8168.           specification:
  8169.           http://java.sun.com/docs/books/jls/html/6.doc.html#11186
  8170.         o Also take a look at Doug Lea's draft coding standard:
  8171.           http://gee.cs.oswego.edu/dl/html/javaCodingStd.html
  8172.  
  8173.   2. (Sect. 18) How do I convert a String to an int?
  8174.  
  8175.      [*] There are several ways. The most straightforward is:
  8176.  
  8177.          String mystring = numString.trim();
  8178.          int i = Integer.parseInt(myString);
  8179.          long l = Long.parseLong(myString)
  8180.  
  8181.  
  8182.      or
  8183.  
  8184.          String mystring = numString.trim();
  8185.          i = Integer.parseInt(myString,myIntRadix);
  8186.  
  8187.  
  8188.      Note 1: There is a gotcha with parseInt - it will throw a
  8189.      NumberFormatException for String values in the range "80000000" to
  8190.      "ffffffff". You might expect it to interpret them as negative, but it
  8191.      does not. The values have to be "-80000000" .. "-ffffffff" to be
  8192.      properly recognized as negative values. This is true for all radixes.
  8193.      According to Bug Parade bug report 4068580, the proper way to generate
  8194.      negative-valued hex Strings for eventual use by parseInt() is with
  8195.      Integer.toString(i, 16). Once that high "sign bit" is on, without the
  8196.      accompanying character, parseInt() says "too big".
  8197.      Note 2: There are similar methods for Byte, Short, and Long. Use
  8198.      myString.trim() to get rid of unwanted spaces before the conversion.
  8199.      Some of the parse methods can cope with spaces, others can't. They were
  8200.      written by two different people.
  8201.  
  8202.          int i = Integer.valueOf(my_str).intValue();
  8203.  
  8204.  
  8205.      also works but involves the creation of an extra object. Note: the
  8206.      pre-FCS JDK 1.2 documentation at one point said that parseDouble and
  8207.      parseFloat methods were to be introduced, but this does not seem to be
  8208.      the case (see bug 4160672). JDK 1.2.
  8209.  
  8210.          float f = Float.valueOf(my_str).floatValue();
  8211.          double d = Double.valueOf(my_str).doubleValue();
  8212.  
  8213.  
  8214.   3. (Sect. 18) How do I convert an int to a string?
  8215.  
  8216.      [*] Try any of these:
  8217.  
  8218.          String s = String.valueOf(i);
  8219.  
  8220.  
  8221.      or
  8222.  
  8223.          String s = Integer.toString(i);
  8224.  
  8225.  
  8226.      or
  8227.  
  8228.          String s = Integer.toString(i, radix);
  8229.  
  8230.  
  8231.      or
  8232.  
  8233.          // briefer but may result in extra object allocation.
  8234.          String s = "" + i;
  8235.  
  8236.  
  8237.      Note: There are similar classes for Double, Float, Long, etc.
  8238.  
  8239.   4. (Sect. 18) How do I print the hex value of an int?
  8240.  
  8241.      [*] You can print the hex equivalent of an int with:
  8242.  
  8243.          int i = 0xf1;
  8244.          System.out.println("i is hex " + Integer.toHexString(i) );
  8245.  
  8246.  
  8247.      OK, how do I read a hex string into an int?
  8248.  
  8249.          int i = Integer.valueOf(myHexString, 16).intValue();
  8250.  
  8251.  
  8252.   5. (Sect. 18) How can you send a function pointer as an argument?
  8253.  
  8254.      [*] Simple answer: use a "callback". Make the parameter an interface
  8255.      and pass an argument instance that implements that interface.
  8256.  
  8257.          public interface CallShow { public void Show( ); }
  8258.  
  8259.          public class ShowOff implements CallShow {
  8260.              public void Show( ) { .... }
  8261.  
  8262.          public class ShowOff2 implements CallShow {
  8263.              public void Show( ) { .... }
  8264.  
  8265.          public class UseShow {
  8266.              CallShow savecallthis;
  8267.  
  8268.              UseShow( CallShow withthis ) {
  8269.                  savecallthis = withthis;
  8270.              }
  8271.  
  8272.              void ReadyToShow( ) { savecallthis.Show( ); }
  8273.          }
  8274.  
  8275.          // in some other class that uses all this stuff:
  8276.          UseShow use_1 = new UseShow( new ShowOff() );
  8277.          UseShow use_2 = new UseShow( new Showoff2() );
  8278.  
  8279.  
  8280.      and then the ReadyToShow() method on use_1 or use_2 will call the
  8281.      appropriate method, as if you had stored a pointer to the method.
  8282.  
  8283.   6. (Sect. 18) How do I execute a command from Java?
  8284.  
  8285.      [*] Use
  8286.  
  8287.          Runtime.getRuntime().exec( myCommandString )
  8288.  
  8289.  
  8290.      where myCommandString is something like "/full/pathname/command". An
  8291.      applet will need to be signed in order to allow this.
  8292.  
  8293.      Note, there is a gotcha associated with reading output from commands.
  8294.      When the runtime exec's the process, it passes to it 3 streams, for
  8295.      stdin, stdout, and stderr; the out and err are buffered but the buffer
  8296.      size isn't very big. When your process runs, it reads (if needed) from
  8297.      in, and writes to out and err. If it doesn't write more than the
  8298.      buffer-size, it can run to completion.
  8299.  
  8300.      But if it tries to write more data to one or the other stream than the
  8301.      buffer can hold, the write blocks, and your process hangs, waiting for
  8302.      you to empty the buffer so it can write some more.
  8303.  
  8304.      So after the exec call, get the streams, and read from them in a loop
  8305.      until they both hit end-of-stream (don't block on either one, just read
  8306.      whatever is available from each, each loop iteration). Then when the
  8307.      streams have ended, call the process.waitFor() method to let it finish
  8308.      dying.
  8309.  
  8310.   7. (Sect. 18) How do I do I/O redirection in Java using exec()?
  8311.  
  8312.      [*] This solution works on Unix platforms using either JDK 1.0.2, or
  8313.      JDK 1.1. The trick is to use an array of Strings for the command line:
  8314.  
  8315.          String[] command = {"/bin/sh", "-c", "/bin/ls > out.dat"};
  8316.  
  8317.  
  8318.      If you don't do this, and simply use a single string, the shell will
  8319.      see the -c and /bin/ls and ignore everything else after that. It only
  8320.      expects a single argument after the -c.
  8321.  
  8322.          import java.io.*;
  8323.          import java.util.*;
  8324.  
  8325.          class IoRedirect {
  8326.          public static void main(String Argv[]) {
  8327.              try {
  8328.                  String[] command = {"/bin/sh", "-c", "/bin/ls > out.dat"};
  8329.                  Process p = Runtime.getRuntime().exec(command);
  8330.                  p.waitFor();
  8331.                  System.out.println("return code: "+ p.exitValue());
  8332.              } catch (IOException e) {
  8333.                  System.err.println("IO error: " + e);
  8334.              } catch (InterruptedException e1) {
  8335.                  System.err.println("Exception: " + e1.getMessage());
  8336.              }
  8337.          }
  8338.          }
  8339.  
  8340.  
  8341.   8. (Sect. 18) So why can't I exec common DOS commands this way (as in
  8342.      18.7)?
  8343.  
  8344.      [*] The reason is that many of the DOS commands are not individual
  8345.      programs, but merely "functions" of command.com. There is no DIR.EXE or
  8346.      COPY.EXE for example. Instead, one executes the command processor
  8347.      (shell) explicitly with a request to perform the built-in command, like
  8348.      so:
  8349.      Runtime.getRuntime().exec("command.com /c dir") for example. On NT, the
  8350.      command interpreter is "cmd.exe", so the statement would be
  8351.      Runtime.getRuntime().exec("cmd /c dir") And you could bring the command
  8352.      output into the program with code like:
  8353.  
  8354.      Process p = runtime.exec ("cmd /c dir");
  8355.      DataInputStream procIn = new DataInputStream(p.getInputStream());
  8356.      while ( true ) {
  8357.         String line = procIn.readLine();
  8358.         if ( line == null ) break;
  8359.         // do something with lin
  8360.      }
  8361.  
  8362.      This situation occurs on any OS where some commands are actually
  8363.      interpreted directly by the shell.
  8364.  
  8365.   9. (Sect. 18) OK, how do I read the output of a command?
  8366.  
  8367.      [*] As above (18.6, 18.7), adjusted like this:
  8368.  
  8369.          BufferedReader pOut= new BufferedReader(
  8370.          new InputStreamReader(p.getInputStream()));
  8371.          try {
  8372.          String s = pOut.readLine();
  8373.          while (s != null) {
  8374.              System.out.println(s);
  8375.              s = pOut.readLine();
  8376.          }
  8377.          } catch (IOException e) { }
  8378.  
  8379.  
  8380.      Another possibility is to read chunks of whatever length as they come
  8381.      in:
  8382.  
  8383.          ...
  8384.  
  8385.          p = r.exec(cmd);
  8386.          InputStream is = p.getInputStream();
  8387.          int len;
  8388.          byte buf[] = new byte[1000];
  8389.          try {
  8390.              while( (len = is.read(buf)) != -1 ) {
  8391.                  String str = new String(buf,0,0,len);
  8392.                  System.out.println( "Process out: " + str );
  8393.              }
  8394.          } catch( java.io.EOFException eof ) { ...
  8395.          } catch( java.io.IOException ioe ) { ...  }
  8396.  
  8397.  
  8398.      However, you cannot read output from some DOS commands on Windows
  8399.      95/98. This is bug 4211683 at Sun, but it is actually a Microsoft
  8400.      bug/poor design. Windows programs that explicitly use a handle to the
  8401.      console ("CON" or "CON:") instead of stdin and stdout cannot be used as
  8402.      subprocesses to Java. The Win95 FTP program is an example of such a
  8403.      program. Windows provides no convenient way for Java to redirect the
  8404.      input and output of such processes from the console to input and output
  8405.      pipes. The only workaround is to use a different implementation of the
  8406.      program that does not use the console directly.
  8407.  
  8408.      Microsoft documents a difference in DOS Console stream handling between
  8409.      95 and NT: see
  8410.      http://support.microsoft.com/support/kb/articles/q150/9/56.asp
  8411.  
  8412.      So capturing output from GNU ls on Win95 works, but the output from
  8413.      "command.com /c dir" is not captured.
  8414.  
  8415.  10. (Sect. 18) How do I compile code which has a cyclic dependency, i.e
  8416.      class pkg1.X contains a reference to class pkg2.Y ?
  8417.  
  8418.      [*] You throw both classes at the compiler at the same time.
  8419.      javac pkg1/X.java pkg2/Y.java
  8420.  
  8421.  11. (Sect. 18) What is the point of creating the temporary reference to
  8422.      this.layoutMgr?
  8423.  
  8424.      [*] This code is from the 1.0 AWT, and the programmer was probably
  8425.      pretty skilled.
  8426.  
  8427.          public synchronized void layout() {
  8428.               LayoutManager layoutMgr = this.layoutMgr;
  8429.               if (layoutMgr != null) {
  8430.                   layoutMgr.layoutContainer(this);
  8431.               }
  8432.          }
  8433.  
  8434.  
  8435.      The code makes a local copy of a global variable for one or both of two
  8436.      reasons.
  8437.      The first reason is that accessing local variables can be faster than
  8438.      accessing (non final) member variables. It's good for loops or where
  8439.      there are many references in the source.
  8440.      The second reason is so that even if other threads update the global,
  8441.  
  8442.          this.layoutMgr = someOtherLayoutMgr;
  8443.  
  8444.  
  8445.      This method will still have a pointer to the original layoutMgr.
  8446.      If the local variable were omitted, and another thread used the
  8447.      setLayout() method to change layoutMgr to null between when the layout
  8448.      method checked for null and when it invoked layoutMgr's layoutContainer
  8449.      method, a NullPointerException would result.
  8450.      Note that the synchronized keyword on the layout method doesn't help
  8451.      any, since setLayout (which could make such a dire change) isn't
  8452.      synchronized. Synchronized methods only lock out other synchronized
  8453.      methods on this object. (The unhelpful synchronized keyword on the
  8454.      layout method is gone in JDK 1.1.)
  8455.      There are two alternative solutions. One would be to make setLayout
  8456.      synchronized and make layoutMgr private, so that it can't be set other
  8457.      ways. This provides a stronger form of thread serialization, in that
  8458.      you would never be able to see an old layout manager being used after
  8459.      it had been replaced. However, it is slower. Another option that
  8460.      provides no increase in thread serialization over the original would be
  8461.      to catch the NullPointerException.
  8462.      Threaded programming is hard! This idiom was probably put in place by
  8463.      someone who got really bitten by this in the past.
  8464.  
  8465.  12. (Sect. 18) What is the difference between "a & b" and "a && b" ?
  8466.  
  8467.      [*] "a & b" takes two boolean operands, or two integer operands. It
  8468.      always evaluates both operands. For booleans, it ANDs both operands
  8469.      together producing a boolean result. For integer types, it bitwise ANDs
  8470.      both operands together, producing a result that is the promoted type of
  8471.      the operands (i.e. long, or int). "|" is the corresponding bitwise OR
  8472.      operation. "^" is the corresponding bitwise XOR operation.
  8473.  
  8474.      "a && b" is a "conditional AND" which only takes boolean operands. It
  8475.      always avoids evaluating its second operand if possible. If a is
  8476.      evaluated to false, the AND result must be "false" and the b operand is
  8477.      not evaluated. This is sometimes called "short-circuited" evaluation.
  8478.      "||" is the corresponding short-circuited OR operation.
  8479.  
  8480.      Possible mnemonic: The longer operators "&&" or "||" try to shorten
  8481.      themselves by not evaluating the second operator if they can.
  8482.  
  8483.  13. (Sect. 18) If I create a thread, and then null out the reference to it,
  8484.      what happens to the thread? Does it get interrupted or what?
  8485.  
  8486.      [*] The code looks like this:
  8487.  
  8488.          Thread t = new Thread( my_runnable_obj );
  8489.          t.start();
  8490.          ...
  8491.          t = null; // what happens to the thread?
  8492.  
  8493.  
  8494.      The answer is that you may no longer have a reference to the thread,
  8495.      but the JVM still does. Once a thread is started, and as long as it
  8496.      keeps running, it is a root object. Root objects are the starting
  8497.      points for "things in use" that the garbage collector uses.
  8498.  
  8499.  14. (Sect. 18) How can a Java program determine the level of JDK support
  8500.      given by the underlying VM? I.e. is it running in a JDK 1.0.2 or 1.1
  8501.      VM?
  8502.  
  8503.      [*] Look at the java.version system property with:
  8504.  
  8505.          String ver = System.getProperty("java.version");
  8506.  
  8507.  
  8508.      There isn't a lot of standardization on the string contents however.
  8509.      Another possibility is to try { ... } to load a class that is unique to
  8510.      one release, like this:
  8511.  
  8512.      boolean isJDK1_1 = true;
  8513.      try {
  8514.          // java.awt.Cursor is available only in the 1.1.x JDK
  8515.          Class cls = Class.forName("java.awt.Cursor");
  8516.      } catch (Exception e)    {
  8517.          // we should have written 'ClassNotFoundException e',
  8518.          // but Communicator generates security exception instead.
  8519.          isJDK1_1 = false;
  8520.      }
  8521.  
  8522.      This approach has the advantage that it can be compiled by any version
  8523.      compiler.
  8524.  
  8525.  15. (Sect. 18) How can I set a system property?
  8526.  
  8527.      [*] JDK 1.2 has
  8528.  
  8529.          System.setProperty( "property", "new value" );
  8530.  
  8531.  
  8532.      Until then, you can get all the properties, and set just the one you
  8533.      want with code like this:
  8534.  
  8535.          System.getProperties().put("property", "new value" );
  8536.  
  8537.  
  8538.  16. (Sect. 18) How can I clone using serialization?
  8539.  
  8540.      [*] Look at the code below, submitted by expert programmer John Dumas.
  8541.      It uses serialization to write an object into a byte array, and reads
  8542.      it back to reconstitute a fresh copy. This is a clever hack!
  8543.  
  8544.      import java.io.ByteArrayOutputStream;
  8545.      import java.io.ByteArrayInputStream;
  8546.      import java.io.ObjectOutputStream;
  8547.      import java.io.ObjectInputStream;
  8548.  
  8549.      public class Cloner {
  8550.         private Cloner() {}
  8551.  
  8552.         public static Object cloneObject(Object o) throws Exception {
  8553.            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  8554.            ObjectOutputStream out     = new ObjectOutputStream(bOut);
  8555.  
  8556.            out.writeObject(o);
  8557.  
  8558.            ByteArrayInputStream bIn =
  8559.                     new ByteArrayInputStream(bOut.toByteArray());
  8560.            ObjectInputStream in     = new ObjectInputStream(bIn);
  8561.  
  8562.            return(in.readObject());
  8563.         }
  8564.  
  8565.         public static void main(String args[]) throws Exception {
  8566.            java.util.Vector v = new java.util.Vector();
  8567.            v.addElement(new StringBuffer("Hello"));
  8568.  
  8569.            java.util.Vector vClone =
  8570.                       (java.util.Vector)Cloner.cloneObject(v);
  8571.  
  8572.            // Changing the StringBuffer int the cloned vector has no
  8573.            // effect on the original StringBuffer object --
  8574.            // demonstrating that we have indeed done a deep copy
  8575.  
  8576.            ((StringBuffer)vClone.elementAt(0)).append(" world");
  8577.  
  8578.            StringBuffer sb = (StringBuffer)v.elementAt(0);
  8579.            System.out.println(sb.toString());
  8580.  
  8581.            sb = (StringBuffer)vClone.elementAt(0);
  8582.            System.out.println(sb.toString());
  8583.  
  8584.            int array[] = { 1, 2, 3, 4, 5 };
  8585.  
  8586.            int arrayClone[] = (int [])Cloner.cloneObject(array);
  8587.  
  8588.            // Again, changes to an element in the cloned array do not
  8589.            // have any effect on the original
  8590.  
  8591.            arrayClone[0]++;
  8592.  
  8593.            System.out.println(array[0]);
  8594.            System.out.println(arrayClone[0]);
  8595.         }
  8596.      }
  8597.  
  8598.      The main() routine is just a driver. All the cleverness is in the very
  8599.      brief cloneObject(). It does a "deep" clone, which is what you usually
  8600.      want (though Java gives you a "shallow" clone by default).
  8601.  
  8602.                        -------------------------------
  8603.  
  8604. 19. Java GOTCHA'S
  8605.  
  8606.   1. (Sect. 19) What is a "GOTCHA" (for non-English native speakers)?
  8607.  
  8608.      [*] It is an abbreviation of "Got you!" It is the triumphant
  8609.      exclamation that a bug or programming idiom makes as it traps the
  8610.      unwary programmer. This section details some of the popular "gotcha's"
  8611.      of Java.
  8612.  
  8613.      See also the list of Java Gotcha's at
  8614.      http://mindprod.com/gloss.html
  8615.  
  8616.   2. (Sect. 19) Why can't I filter filenames with the accept() method?
  8617.  
  8618.      [*] It's a known bug. FileDialog doesn't call FilenameFilter.accept().
  8619.      The bug id is 4031440, and it can be seen at the Java Developer
  8620.      Connection.
  8621.  
  8622.      There is no way to implement FilenameFilter support with the current
  8623.      reliance on the Win32 common file dialog. To support FilenameFilter,
  8624.      the FileDialog needs to issue a callback for each file it wants to
  8625.      display, which the FilenameFilter can veto. But the Win32 common
  8626.      FileDialog doesn't have any way to issue callbacks. Instead it accepts
  8627.      simple wildcard patterns for choosing files which match a certain
  8628.      pattern. That's a reasonable alternative to FilenameFilters, but that
  8629.      model isn't supported by the current Java API.
  8630.  
  8631.      JFC has a JFileChooser class that is a better bet for you to use for
  8632.      file dialogs. It works fine.
  8633.  
  8634.   3. (Sect. 19) I changed a final value, and recompiled just the file that
  8635.      it was in, and the entire rest of the program used the old value!
  8636.  
  8637.      [*] This is the "expected" behavior. If you have this in one file
  8638.  
  8639.      class Flags { final static boolean debug = true; }
  8640.  
  8641.      and you change it to, and recompile just this file:
  8642.  
  8643.      class Flags { final static boolean debug = false; }
  8644.  
  8645.      Then the rest of your Java .class files will still see it as "true".
  8646.  
  8647.      When you declare a "static final int" (or any other primitive), the
  8648.      compiler turns that into a compile time constant whose value can be
  8649.      substituted wherever it is used in your program. If you update the
  8650.      value in the source file, you'll need to recompile every class that
  8651.      uses it.
  8652.  
  8653.      See Java Language Specification, section 13.4.8 "final Fields and
  8654.      Constants": "We call a field that is static, final, and initialized
  8655.      with a compile-time constant expression a primitive constant. If a
  8656.      field is a primitive constant, then deleting the keyword final or
  8657.      changing its value will not break compatibility with pre-existing
  8658.      binaries by causing them not to run, but they will not see any new
  8659.      value for the constant unless they are recompiled."
  8660.  
  8661.   4. (Sect. 19) What is the "substring trap"?
  8662.  
  8663.      [*] The "substring trap" is the name for a mistake that is all too easy
  8664.      to make when using the substring() method of class String. The method
  8665.      signature is:
  8666.  
  8667.      public String substring(int beginIndex, int endIndex)
  8668.  
  8669.      The name "endIndex" suggests that is the index where the Substring
  8670.      ends.
  8671.  
  8672.      But in fact, the substring extends only to the character at position
  8673.      (endIndex-1)! It seems to be done this way so that
  8674.      s.substring(0,s.length()) is equal to s. If so, the name of the second
  8675.      parameter should be something like endInxLessOne or Length. But not the
  8676.      confusing and misleading endIndex. Beware the substring trap.
  8677.  
  8678.   5. (Sect. 19) Why does getGraphics() return null on my offscreen image?
  8679.  
  8680.      [*] The following code
  8681.  
  8682.      class MyFrame extends Frame {
  8683.        MyFrame() {
  8684.          Image offscreen = createImage(100,100);
  8685.          Graphics offg = offscreen.getGraphics();
  8686.          }
  8687.        ...
  8688.        }
  8689.  
  8690.      will usually not work, since the peer will not exist at this time.
  8691.      Without the peer for the Frame, you cannot succeed in creating
  8692.      offscreen Images. (There's no problem creating Produced Images without
  8693.      a peer. Trying to draw them, of course, is another matter).
  8694.  
  8695.      One "standard" form of offscreen code looks like this: (note the reuse
  8696.      of the Graphics and Image objects for as long as possible)
  8697.  
  8698.      class Gumble extends java.awt.Something {
  8699.        private Image offi;
  8700.        private Graphics offg;
  8701.  
  8702.        public void update(Graphics g) {
  8703.          if (g == null) return; // Paranoia
  8704.          Dimension size = size();
  8705.          if (    offi == null
  8706.               || offi.getWidth()!=size.width
  8707.               || offi.getHeight()!=size.height  ) {
  8708.            if (offg!=null) offg.dispose();
  8709.            offi = createImage(size.width, size.height);
  8710.            offg = offi.getGraphics();
  8711.            // Regenerate offi here...
  8712.            }
  8713.          // If you use getClipBounds() here,
  8714.          // check that for being null, too!
  8715.          // several implementations have been known to pass them....
  8716.          g.drawImage(offi);
  8717.          }
  8718.  
  8719.        public void paint(Graphics g) {
  8720.          update(g);
  8721.          }
  8722.        }
  8723.  
  8724.      See also Question 8.7
  8725.  
  8726.   6. (Sect. 19) The dynamic type of a method argument doesn't seem to be
  8727.      used to choose an overridden method at runtime.
  8728.  
  8729.      [*] Correct. Generally, if you invoke a method on an object, the
  8730.      object's actual runtime type, not the type of the reference that you
  8731.      used to reference it, determines which method is invoked. This is
  8732.      regular polymorphism.
  8733.  
  8734.      It's not the same for object parameters: the compiler decides at
  8735.      compile time, depending on the types of the parameter expressions,
  8736.      which method signature to use, and this is "hardwired" into the
  8737.      bytecode. The compiler does not look at the object argument at runtime
  8738.      and say "ah, this is a derived type, so I will choose the method that
  8739.      takes the derived type as an argument."
  8740.  
  8741.      This is best seen in a code example:
  8742.  
  8743.      class Base { }
  8744.      class Derived extends Base { }
  8745.  
  8746.      public class foo {
  8747.  
  8748.         public static void method(Base b) {
  8749.           System.out.println("In the base method...");
  8750.         }
  8751.  
  8752.         public static void method(Derived d) {
  8753.           System.out.println("In the derived method...");
  8754.         }
  8755.  
  8756.         public static void test(Base b) {
  8757.           if (b instanceof Derived)
  8758.             System.out.print("Derived:  ");
  8759.           else
  8760.             System.out.print("Base:     ");
  8761.  
  8762.           method(b);   // which method?  method(base) or method(derived)?
  8763.         }
  8764.  
  8765.         public static void main(String args[]) {
  8766.           Base b = new Base();
  8767.           Derived d = new Derived();
  8768.  
  8769.           System.out.println("test calls.");
  8770.           test(b);
  8771.           test(d);
  8772.         }
  8773.      }
  8774.  
  8775.      Running the program gives an output of
  8776.  
  8777.      test calls.
  8778.      Base:     In the base method...
  8779.      Derived:  In the base method...
  8780.  
  8781.      See JLS section 15.11.4.4 and 15.11.3:
  8782.      "If class S contains a declaration for a method named m with the same
  8783.      descriptor (same number of parameters, the same parameter types, and
  8784.      the same return type) required by the method invocation as determined
  8785.      at compile time then this is the method to be invoked."
  8786.  
  8787.   7. (Sect. 19) Why did I lose my updates when I changed data fields in a
  8788.      graph that I was serializing?
  8789.  
  8790.      [*] Quoting from the object serialization specification at:
  8791.      http://www.javasoft.com/products/jdk/1.1/docs/
  8792.      guide/serialization/spec/serial-arch.doc.html#4176
  8793.           The writeObject method serializes the specified object and
  8794.           traverses its references to other objects in the object graph
  8795.           recursively to create a complete serialized representation of the
  8796.           graph.
  8797.  
  8798.           Within a stream, the first reference to any object results in the
  8799.           object being serialized or externalized and the assignment of a
  8800.           handle for that object. Subsequent references to that object are
  8801.           encoded as the handle.
  8802.  
  8803.      In other words, changing an object and then writing it again does not
  8804.      really write it twice. Instead it just writes a reference back to the
  8805.      first occurrence, losing any fields that have changed in the meantime.
  8806.  
  8807.      There are three ways around this: (1) (inefficient) Reset (or close and
  8808.      reopen) the stream, and start again by writing the new value of the
  8809.      object. This is drastic -- you are throwing away all the serialization
  8810.      that you have already done.
  8811.      (2) (kludgey) Create a new object and write that.
  8812.      (3) (could be a lot of work) Write your own protocol for object
  8813.      serialization. Have something like a data stream where the contents of
  8814.      an object are marked by special identifiers. Each "end" of the stream
  8815.      can decide whether it will use a new object each time or reuse an
  8816.      existing object.
  8817.  
  8818.   8. (Sect. 19) When I click on a Java window frame, it doesn't close!
  8819.  
  8820.      [*] You need to add the code to listen for a window closing event, and
  8821.      take the appropriate action (hide the window, exit the program if the
  8822.      top level frame, etc).
  8823.  
  8824.      The window closing event handler is simple:
  8825.  
  8826.      Frame mf = new Frame("binky");
  8827.      mf.addWindowListener( new WindowAdapter() {
  8828.          public void windowClosing(WindowEvent we) {
  8829.              System.exit(0); // or setVisible(false); etc.
  8830.          } });
  8831.  
  8832.      This really should be the default behavior of an AWT Frame. So you'll
  8833.      be delighted to hear that JavaSoft has "made it so" for the JFrame
  8834.      Swing component. That leads to a slightly different problem. See
  8835.      Question 4.3.3. See also Question 13.9.
  8836.  
  8837.   9. (Sect. 19) What's the deal with "super"? How far back into parent
  8838.      classes can I go?
  8839.  
  8840.      [*] The most common use of super is the call "super()" to invoke a
  8841.      constructor in the superclass. The keyword "super" is also used to
  8842.      access fields of any superclass (not just the immediate superclass)
  8843.      that are hidden by an identically named feature in the current class.
  8844.  
  8845.      However there is no way to "chain" several super's together, and reach
  8846.      back higher into the parent class hierarchy. E.g. do not think that
  8847.      "super.x" means the "x of parent" and "super.super.x" means the "x of
  8848.      grandparent". This is a very common mistake. There is no
  8849.      "super.super.x". Looking at the generated byte code, if you have
  8850.  
  8851.      class Parent {        }
  8852.  
  8853.      class Child extends Parent {       }
  8854.  
  8855.      then, in Child "super.someParentMethod();" means "invokespecial
  8856.      X.someParentMethod()" in the JVM, not "invokevirtual".
  8857.      Invokespecial means "call the exact method I am telling you."
  8858.      Invokevirtual means "call the right method for whatever object this
  8859.      is".
  8860.  
  8861.  10. (Sect. 19) When I change some component (e.g. a new label on a button)
  8862.      I don't see the change on the screen immediately even if I repaint().
  8863.  
  8864.      [*] You need to add a call to the paintImmediately(x,y,w,h) method of
  8865.      JComponent. That repaints the component completely before continuing
  8866.      execution. On pre-JDK 1.2 systems, use:
  8867.  
  8868.      invalidate();
  8869.      validate();
  8870.  
  8871.      They cause the component hierarchy to be marked as needing to be laid
  8872.      out again, and the validate causes that to be done. It may be
  8873.      expensive, but is a way of getting the peers to recalculate size and to
  8874.      do what is needed to bring the display up to date. It has limitations:
  8875.      it doesn't cause an immediate screen update when invoked from an event
  8876.      handler, where paintImmediately() does.
  8877.  
  8878.  11. (Sect. 19) Why aren't popup menus working cross-platform for me?
  8879.  
  8880.      [*] On Windows, the pop-up trigger is a mouse release (except in
  8881.      certain programs like Netscape Communicator). On Unix, the pop-up
  8882.      trigger is a mouse press.
  8883.  
  8884.      Therefore you need to ask the question isPopupTrigger() in both the
  8885.      mousePressed() and mouseReleased() methods when implementing the
  8886.      MouseListener interface. Alternatively override Component's
  8887.      processMouseEvent as a central place for handling mouse input.
  8888.  
  8889.  12. (Sect. 19) Why aren't newlines working cross-platform for me?
  8890.  
  8891.      [*] Code like this:
  8892.  
  8893.      if (c == '\n')
  8894.           fin = true;
  8895.  
  8896.      is not cross-platform. On Unix the line terminator is "\n", on Windows,
  8897.      it is frequently "\r\n", on the Mac it is "\r".
  8898.  
  8899.      The call System.getProperty("line.separator") will return a string
  8900.      containing the platform-specific line separator character(s), and you
  8901.      then need to compare it according to how your data is formatted (e.g.
  8902.      compare 2 characters or one). There is also a property for the
  8903.      separator character in file pathnames, and other values too.
  8904.  
  8905.      This can screw-up your networking programs too. Most ASCII based
  8906.      protocols like HTTP expect \r\n to terminate a request. They will hang
  8907.      on a request from a Mac that only sends \r.
  8908.  
  8909.  13. (Sect. 19) Why didn't my text display in my GUI? Is the Inset wrong?
  8910.  
  8911.      [*] The most common Inset problem is not an Inset problem at all, but
  8912.      rather that people just assume the x,y location of a
  8913.      Graphics.drawString() actually refers to the top left part of the
  8914.      string image. In fact it refers to the baseline. So you'll need to take
  8915.  
  8916.      g.drawString("Hello World",0,getFontMetrics(getFont()).getAscent());
  8917.  
  8918.  14. (Sect. 19) Why did my polygon come out the wrong shape?
  8919.  
  8920.      [*] This question and answer comes directly off
  8921.      comp.lang.java.programmer, and deserves to be immortalized for
  8922.      posterity.
  8923.      When I use fillPolygon with the following points I get two inverted
  8924.      triangles instead of a rectangle. Why?
  8925.  
  8926.      int xPoints[] = {71, 78, 71, 78};
  8927.      int yPoints[] = {147, 147, 130, 130};
  8928.      g.fillPolygon(xPoints, ypoints, xPoints.length);
  8929.  
  8930.      Developer Felix Pahl supplied the answer in limerick form:
  8931.         o A developer (for details bored her)
  8932.           didn't follow the polygon's border
  8933.           so instead of right angles
  8934.           she got two triangles
  8935.           'cause the endpoints were in the wrong order!
  8936.  
  8937.      You must put the points in the order you would encounter them in if you
  8938.      went round the polygon's border. The filling algorithm is doing the
  8939.      right thing! Try drawing the points on paper to see:
  8940.  
  8941.      71,130   78,130
  8942.        O--------O
  8943.        |        |
  8944.        |        |
  8945.        |        |
  8946.        o--------o
  8947.      71,147   78,147
  8948.  
  8949.      Under JDK1.1, the two endpoints are connected automatically and you
  8950.      would order the array elements as:
  8951.  
  8952.      int xPoints[] = { 71,  78,  78,  71};
  8953.      int yPoints[] = {130, 130, 147, 147};
  8954.  
  8955.      Under JDK1.0.2, you have to explicitly connect the two endpoints, and
  8956.      you would write the array elements as:
  8957.  
  8958.      int xPoints[] = { 71,  78,  78,  71,  71};
  8959.      int yPoints[] = {130, 130, 147, 147, 130};
  8960.  
  8961.  15. (Sect. 19) Why can't I see all the components I added to a Frame?
  8962.  
  8963.      [*] If you have code like:
  8964.  
  8965.      Frame myframe = new Frame("Child Frame");
  8966.      myframe.resize(512,384);
  8967.      myframe.add(new Label("Child"));
  8968.      myframe.show();
  8969.  
  8970.      The default layout manager for Frame is BorderLayout. Components
  8971.      positioned with a BorderLayout should include a positioning constant to
  8972.      be correct. If you don't include one, "-1" is assumed, which causes the
  8973.      component to go to the end of the list, and possibly be buried (in
  8974.      terms of z-order) under any other components you add. So, change the
  8975.      add to
  8976.  
  8977.      myframe.add("Center", new Label("Child"));
  8978.  
  8979.      and all will be well.
  8980.  
  8981.  16. (Sect. 19) Why do I get the wrong results when I compare two Strings
  8982.      together?
  8983.  
  8984.      if (s1 == s2)
  8985.  
  8986.      is giving me funny results.
  8987.  
  8988.      [*] The comparison using "==" on objects, like Strings, is asking the
  8989.      question "do these two objects have the same reference?". That is, do
  8990.      they have the same address, and hence are not two object but one? What
  8991.      you most probably meant is "do these two Strings have the same
  8992.      contents?" which you can express this way:
  8993.  
  8994.      if ( s1.equals(s2) )
  8995.  
  8996.      This is a very, very easy mistake to make and impossible to spot until
  8997.      you have had it explained to you.
  8998.  
  8999.      People talk about "interning" a String. That means calling the intern()
  9000.      method on a String. This places the String in the runtime constant pool
  9001.      if it was not already there. The compiler is required to intern() all
  9002.      literal Strings. If you intern() all your Strings as well then all
  9003.      duplicates are shared and comparisons can be done by the (much faster)
  9004.      address comparison rather than content comparison. It's a performance
  9005.      optimization. See also Q3.22.
  9006.  
  9007.      Note that this comparison error also occurs with other objects, not
  9008.      just Strings. The code:
  9009.  
  9010.              if (getBackground() == Color.black)
  9011.  
  9012.  
  9013.      is a test for object identity, rather than content identity. It will
  9014.      work if you originally setBackground(Color.black). To avoid difficult
  9015.      debugging in the future, you almost certainly want to say
  9016.  
  9017.              if (getBackground().equals( Color.black ) )
  9018.  
  9019.  
  9020.      or even (in this visual case) compare the darkness of the RGB values of
  9021.      the pixels.
  9022.  
  9023.  17. (Sect. 19) Why doesn't final prevent my object from changing?
  9024.  
  9025.      [*] You have code like this
  9026.  
  9027.      final StringBuffer s = new StringBuffer("don't change me");
  9028.       // ...
  9029.      s.append(", but I did");
  9030.      System.out.println(s);
  9031.  
  9032.      And the new value of s is "don't change me, but I did". The reason is
  9033.      that the "final" modifier makes the reference variable (here, s) final,
  9034.      not the object that s points to. It means that the reference variable
  9035.      cannot be changed to point to some other StringBuffer. The state of the
  9036.      StringBuffer can still be modified by calling methods on it or directly
  9037.      assigning to its public fields.
  9038.  
  9039.      The right way to think about final is that it prevents you assigning to
  9040.      that particular variable. The only way to make the fields of an object
  9041.      constant (unchanging) is to make all its data fields private, and not
  9042.      provide any set methods for them, only get methods. Even that won't
  9043.      stop other objects of the same class adjusting it.
  9044.  
  9045.  18. (Sect. 19) Why can't the compiler find my package?
  9046.  
  9047.      [*] When trying to compile a file in a package you get a compiler error
  9048.      like:
  9049.  
  9050.       DBTest.java:10: Class database.Table not found in type declaration.
  9051.  
  9052.      The file Table.java and DBTest.java are in the same directory. They
  9053.      both have "package database;" at the top of the file. The current
  9054.      directory is included in the classpath.
  9055.  
  9056.      The reason is that when compiling packages, you have to be at the 'top'
  9057.      of the directory/package hierarchy. So to compile both Table.java and
  9058.      DBTest.java, you have to be in the directory that contains the database
  9059.      directory (i.e. where the package hierarchy starts), and just:
  9060.  
  9061.             javac database/Table.java
  9062.             javac database/DBTest.java
  9063.  
  9064.  
  9065.      and it should all compile fine.
  9066.  
  9067.  19. (Sect. 19) I have a program with keyboard input and a button. When the
  9068.      user hits the space bar, the button gets pressed as it is in focus!
  9069.  
  9070.      [*] The VM sets the focus on the first traversible object in the UI. If
  9071.      you want the button not to be assigned focus by default, you must
  9072.      subclass the button and override the isFocusTraversable() method to
  9073.      return false.
  9074.  
  9075.      Another approach is to manually set the focus on some other component
  9076.      (say the Frame) when you show the window. To do so you have to jump
  9077.      through hoops to outsmart the VM that is trying to set it on the
  9078.      button. One approach is to listen for the windowActivated event and set
  9079.      a Swing Timer to do a requestFocus() on the frame about 0.1 seconds
  9080.      after the activated message. This seems convoluted, but it is the only
  9081.      thing found that consistently works cross platform.
  9082.  
  9083.      Another reader suggests that if the frame normally gets the focus
  9084.      first, you can override its gotFocus() event and set the focus to the
  9085.      component you want. Don't forget to return true!
  9086.  
  9087.  20. (Sect. 19) What's the hidden size limitation of String serialization?
  9088.  
  9089.      [*] If you wish to Serialize a string, be alert to the restriction
  9090.      that:
  9091.           The size of the String, when UTF-encoded, must be < 64Kb
  9092.      So for robust code you have to examine the String once to ensure that
  9093.      it will be less than 64Kb after encoding, and then have the JVM
  9094.      effectively repeat that work in the process of encoding, when you write
  9095.      it to an ObjectOutputStream.
  9096.  
  9097.      A possible workaround that is to strip the string down to "byte[]" and
  9098.      pass it around in RMI that way. The code with this restriction is in
  9099.      DataOutputStream
  9100.  
  9101.          public final void writeUTF(String str)
  9102.          ...
  9103.          [perform the size-after-conversion-to-UTF computation]
  9104.          ...
  9105.              if (utflen > 65535)
  9106.                  throw new UTFDataFormatException();
  9107.          ...
  9108.  
  9109.      RMI relies on serialization, so RMI has the same String size
  9110.      limitation.
  9111.  
  9112.  21. (Sect. 19) When I change a field in just one object in my array, that
  9113.      field changes in all the objects in my array!
  9114.  
  9115.      [*] Here the problem is probably that you have initialized the array
  9116.      with N references to the same one object.
  9117.  
  9118.      This is easy to overlook, because arrays in Java only contain
  9119.      references to objects, not objects. (Or they can contain primitives).
  9120.  
  9121.  22. (Sect. 19) Do DrawRect and FillRect work on rectangles of the same
  9122.      size?
  9123.  
  9124.      [*] No. java.awt.Graphics.drawRect draws a rectangle that's 1 pixel
  9125.      wider and 1 pixel taller than a rectangle drawn by fillRect.
  9126.  
  9127.  23. (Sect. 19) My executable Jar files don't work!
  9128.  
  9129.      [*] It is possible to exactly follow the instructions given in the
  9130.      documentation and yet still get the following error message when
  9131.      attempting to run the .jar file: "Failed to load Main-Class manifest
  9132.      attribute from myapp.jar"
  9133.  
  9134.      There has to be a carriage return after the Main-Class definition in
  9135.      the manifest file, otherwise it does not work! Example, in a file
  9136.      called manifest.txt:
  9137.  
  9138.      Main-Class: MyClass  // does not work
  9139.  
  9140.      Main-Class: MyClass
  9141.      // does work
  9142.  
  9143.      Then, when the manifest file is merged into the jar file like this:
  9144.  
  9145.      jar cmfv manifest.txt myapp.jar *.class
  9146.  
  9147.      it works fine.
  9148.  
  9149.  24. (Sect. 19) Why do I get the error message "Wrong number of arguments in
  9150.      constructor"
  9151.  
  9152.      [*] Almost certainly, you have written your constructor with a return
  9153.      type or void or something. I.e. you have written:
  9154.  
  9155.           public MyClass Myclass() { ...}
  9156.  
  9157.      instead of:
  9158.  
  9159.           public Myclass() { ...}
  9160.  
  9161.      Giving a constructor a return type makes it into a regular method that
  9162.      happens to have the same name as the class. The language should ideally
  9163.      outlaw this, but it doesn't.
  9164.  
  9165.                        -------------------------------
  9166.  
  9167. 20. Further Resources
  9168.  
  9169.   1. (Sect. 20) Will Java ever be fast enough for games like Quake?
  9170.  
  9171.      [*] Some people originally thought not.
  9172.  
  9173.      Please see the site http://fragisland.fragzone.se/ which has the Frag
  9174.      Island game (a quake-style game) written in 100% Java. You play it as
  9175.      an applet, by browsing the above site. Watch out -- it's noisy!
  9176.  
  9177.   2. (Sect. 20) Are there any commercial/shareware/free Java libraries?
  9178.  
  9179.      [*] Take a look at the Java Collection Framework, a group of classes
  9180.      that are part of Java 1.2. These classes implement general-purpose data
  9181.      structures, and they will become widely used.
  9182.  
  9183.      The documentation for JDK 1.2 explains that the Collection Framework
  9184.      defines three kinds of things:
  9185.         o Standard interfaces representing data structures of various kinds
  9186.           for you to implement. Since these are interfaces, you can use them
  9187.           in your code before you have implemented them.
  9188.         o Partial implementations of those interfaces, saving you some work.
  9189.         o Complete implementations, ready to use for data in your programs.
  9190.  
  9191.      The standard interfaces are Collection, Set, List and Map, plus the
  9192.      more specialised SortedSet and SortedMap. Lists have duplicate elements
  9193.      whereas Sets do not. Finer distinctions such as immutability are
  9194.      defined in the implementor classes, enforced by throwing runtime
  9195.      exceptions. See the JDK 1.2 documentation for a full discussion.
  9196.  
  9197.      For more about sorting prior to JDK 1.2, look at the class SortDemo in
  9198.      the demo directory of the JDK. Alternatively, use one of the several
  9199.      classic sorts available from Roedy Green. They are supplied free with
  9200.      heavily commented Java source code.
  9201.  
  9202.      See "QuickSort", "HeapSort" and "RadixSort" in the Java glossary at
  9203.      http://mindprod.com/index.html.
  9204.  
  9205.      Also, try the Java Generic Library. This library (JGL) is freely
  9206.      downloadable from http://www.objectspace.com/
  9207.  
  9208.      Also Visual Engineering has JChart at: http://www.ve.com. No licensing
  9209.      fees.
  9210.  
  9211.      Visual Numerics has its Java Numeric Library available for download at
  9212.      http://www.vni.com/products/wpd/jnl/jnl_1_0.html. They offer the JNL as
  9213.      a proposed standard library for numerical functions missing from Java.
  9214.  
  9215.   3. (Sect. 20) Why doesn't somebody write a shell in Java? Then they could
  9216.      use it on all platforms!
  9217.  
  9218.      [*] Somebody has done just that. Look at http://www.jsh.net/
  9219.  
  9220.   4. (Sect. 20) Are there any URLs for other libraries?
  9221.  
  9222.      [*] Indeed, there are. The Java3D Repository http://java3d.sdsc.edu/
  9223.  
  9224.   5. (Sect. 20) Are there any URLs for regular expression handlers in Java?
  9225.  
  9226.      [*] There is one from ORO Inc. They dissolved as a corporation, but one
  9227.      of the founders maintains the software at http://www.oroinc.com/.
  9228.      For other sources, see
  9229.      http://www.meurrens.org/ip-Links/Java/regex/index.html
  9230.  
  9231.      And don't forget to check out Lava -- a set of Java classes designed to
  9232.      support programmers who develop console-mode applications and/or C
  9233.      programmers who are converting to Java. The first release of Lava has
  9234.      printf and other text formatting, encryption, parsing and miscellaneous
  9235.      I/O. Lava can be downloaded from http://www.newbie.net/sharky/lava/
  9236.  
  9237.      Also consider the Java version of the Unix find command. It offers
  9238.      Regex filename matching, mindepth, maxdepth, symlink follow / no
  9239.      follow, file type matching all cross-platform. The package is at
  9240.      http://www.rule-of-eight.com/en/components/
  9241.  
  9242.   6. (Sect. 20) Are there any installers for Java? Preferably
  9243.      platform-neutral ones.
  9244.  
  9245.      [*] There are several possibilities.
  9246.         o InstallAnywhere 2 from ZeroG software. See
  9247.           http://www.zerog.com/html/installanywhere_2.html
  9248.           They have a free version for shareware authors.
  9249.         o InstallShield makes a Java version of their installation package.
  9250.           See http://www.installshield.com/java/default.asp
  9251.         o IBM offers a comprehensive Java installer through its alphaworks
  9252.           site http//www.alphaworks.ibm.com/formula/installtoolkit
  9253.         o Denova offers the J'Express installer. There is a free trial
  9254.           version available for download at http://www.denova.com
  9255.           Freeware authors can receive a completely free license to
  9256.           J'Express Standard. Simply fill in the application at
  9257.           http://www.denova.com/JExpress/freeware.html.
  9258.  
  9259.   7. (Sect. 20) What is "Jazilla"?
  9260.  
  9261.      [*] Jazilla is Mozilla (Netscape Communicator free source) ported to
  9262.      Java. In other words, a free source browser that supports Java and
  9263.      Javascript, written in Java!
  9264.  
  9265.      You can get more information, and volunteer to help with the project at
  9266.      http://www.jazilla.org/
  9267.  
  9268.   8. (Sect. 20) Where can I get Java for my Palm Pilot PDA?
  9269.  
  9270.      [*] There is a translator allowing you to compile Java programs for the
  9271.      Palm Pilot PDA! This is an astonishing piece of work as the Pilot has
  9272.      such a small memory footprint. The translator is in an early stage of
  9273.      development, but is available at:
  9274.      http://www.cs.washington.edu/homes/mcdirmid/ghost
  9275.  
  9276.      Try it, or even better, volunteer to help with the project. Details at
  9277.      the website above.
  9278.  
  9279.      There is a Java-PalmPilot Project called "jSyncManager" which allows
  9280.      PalmPilot synchronization and jConduit development in pure Java. See
  9281.      http://yaztromo.idirect.com/java-pilot.html.
  9282.      If you can run Java 1.1 and Sun's Communications API, you can run
  9283.      jSyncManager.
  9284.  
  9285.   9. (Sect. 20) What is "Dippy Bird" and where can I get it?
  9286.  
  9287.      [*] Dippy Bird is Java documentation in WinHelp format, which can be
  9288.      used directly on Windows desktops, and has a searching utility. The
  9289.      developer of the Dippybird project, Bill Bercik, has stopped further
  9290.      work on the project due to lack of time and funds. Instead you can use
  9291.      http://www.confluent.fr/javadoc/JavadocE.htm which has a more up to
  9292.      date Java WinHelp doc.
  9293.      You can get still get the Dippy Bird download at
  9294.      http://www.dippybird.com/jdk111.exe (JDK 1.1). Note that on NT 4.0 you
  9295.      need to change the generated shortcut to point to NT's 32-bit WinHelp.
  9296.  
  9297.  10. (Sect. 20) Are there any Java graphing tools?
  9298.  
  9299.      [*] Take a look at GraphMaker -- a complete full-featured Java
  9300.      application for creating and searching graphs. It is available under
  9301.      GPL with source, and uses the latest Swing JFC features. See
  9302.      http://home.earthlink.net/~nfiedler/graph/
  9303.  
  9304.  11. (Sect. 20) Where can I get icons for use with Java?
  9305.  
  9306.      [*] Public spirited programmer and Java supporter Dean S. Jones has
  9307.      created a collection of over 100 icons for use in Java freeware. They
  9308.      are available on the Java Lobby site at
  9309.      http://webart.javalobby.org/jlicons/.
  9310.  
  9311.  12. (Sect. 20) What is "UML"?
  9312.  
  9313.      [*] UML is the Unified Modeling Language. It is unified in the sense
  9314.      that it draws together ideas from a couple of earlier software design
  9315.      languages. UML is an emerging standard for diagrams of object-oriented
  9316.      classes. It was devised by Grady Booch, Ivar Jacobsen, and James
  9317.      Rumbaugh, and it unifies several popular existing notations.
  9318.  
  9319.      A UML product is available from Rational Software, who also offer a
  9320.      tutorial CD for free. See http://www.rational.com/uml/index.jtmpl There
  9321.      are some whitepapers too, but there don't seem to be any free online
  9322.      tutorials.
  9323.  
  9324.      See http://www.togetherj.com/ for information on Together/J. That is a
  9325.      platform-independent UML product that supports round-trip engineering
  9326.      for Java. Whiteboard version is free.
  9327.  
  9328.  13. (Sect. 20) Where can I get info on Java college courses?
  9329.  
  9330.      [*] The JCampus site at http://www.jcampus.org has links and
  9331.      connections to Java CS Dept. courses, assignments, academic papers and
  9332.      Java-related events. JCampus is a non-profit, online Community for CS
  9333.      Dept. professors, students and staff who are teaching, learning and
  9334.      using the Java programming language.
  9335.  
  9336.  14. (Sect. 20) What is the Java IFAQ?
  9337.  
  9338.      [*] It is the Java list of Infrequently Answered Questions, a FAQ
  9339.      maintained by Peter Norvig, author of the book "Artificial Intelligence
  9340.      - A Modern Approach". Take a look at the Java IFAQ at
  9341.      http://www.norvig.com/java-iaq.html There's a lot of good information
  9342.      in that document.
  9343.  
  9344.  15. (Sect. 20) Are there any Java tools for PDF?
  9345.  
  9346.      [*] PDF (Portable Document Format) is the text publishing format
  9347.      defined by Adobe. Acrobat is the technology to display and print PDF
  9348.      files. Abode supplies the client (document reading) software for free.
  9349.      There is a PDF toolkit written in Java at http://www.etymon.com. Even
  9350.      better it is GPL'd. It is more a toolkit for programmers embedding PDF
  9351.      in their products, than an end-user technology though. It doesn't have
  9352.      a GUI for displaying PDF for example.
  9353.  
  9354.  16. (Sect. 20) Are there any Java info search tools?
  9355.  
  9356.      [*] IBM has a very good search engine for java developers
  9357.      http://www.ibm.com/java
  9358.  
  9359.  17. (Sect. 20) What other languages compile to bytecode?
  9360.  
  9361.      [*] Quite a lot of languages compile to Java bytecode, more than 60 at
  9362.      the last count. See the webpage
  9363.      http://grunge.cs.tu-berlin.de/~tolk/vmlanguages.html
  9364.  
  9365.  18. (Sect. 20) Has anyone written a Java-to-RPC interface, to talk to
  9366.      legacy code?
  9367.  
  9368.      [*] See www.distinct.com. It implements a subset of RPC, and is a
  9369.      commercial, supported product. You can review RFCs 1831 and 1832 for
  9370.      information on the full protocol. Java uses the same endianness as
  9371.      RPC's external data representation (network byte order), so all the
  9372.      Java file reads/writes can be used directly.
  9373.  
  9374.      Netbula recently released Java RPC, a fully compatible port of ONC RPC
  9375.      to Java. The binary package can be downloaded for evaluation from
  9376.      http://netbula.com/javarpc/
  9377.  
  9378.      The specifications are in RFC 1831 (the RPC protocol spec) and RFP 1832
  9379.      (the XDR spec).
  9380.  
  9381.  19. (Sect. 20) Are there any automated tools for Javadoc?
  9382.  
  9383.      [*] Yes. See http://www.mindspring.com/~chroma/docwiz/docwizApplet.html
  9384.      for a Java development tool called DocWiz. It is the easiest way to add
  9385.      JavaDoc comments to your Java code.
  9386.  
  9387.  20. (Sect. 20) Is there any information on XML and Java?
  9388.  
  9389.      [*] Yes. See http://developerlife.com
  9390.      It shows you how to use:
  9391.         o the Sun parser (Sun ProjectX EA2)
  9392.         o the DOM (org.w3c.dom.*) interfaces
  9393.         o JFC/Swing with XML
  9394.         o Servlets with XML
  9395.      and more.
  9396.  
  9397.  21. (Sect. 20) How can I find the format of a .class file/a JPG/a PNG
  9398.      file/any file?
  9399.  
  9400.      [*] There is a great website that maintains descriptions and links to
  9401.      descriptions of hundreds of file formats. The site is at:
  9402.      http://www.wotsit.org/
  9403.      It shows you how the files are structured, and makes it a lot simpler
  9404.      for you to write code that creates/decodes such a file.
  9405.  
  9406.  22. (Sect. 20) Why not start up one copy of the JVM and share it among many
  9407.      Java programs?
  9408.  
  9409.      [*] If the JVM takes about 15MB (say) in overhead, and a program takes
  9410.      3MB, then starting up a fresh JVM for each program is slow and
  9411.      wasteful. If a single copy of the JVM and libraries could instead be
  9412.      shared among multiple Java applications there would be less overhead
  9413.      and everything would run faster.
  9414.  
  9415.      That observation was the guiding force behind the echidna project to
  9416.      support a JVM that could run multiple applications. See the site
  9417.      http://www.javagroup.org/echidna/ for more details.
  9418.  
  9419.  23. (Sect. 20) How can I edit sound files?
  9420.  
  9421.      [*] The JaWavedit java code lets you edit .wav and .au files. It can be
  9422.      found at http://www.bome.com/JaWavedit/. It's free to use.
  9423.  
  9424.      If you are inspired to write freeware like this yourself, many file
  9425.      formats are explained and described at http://www.wotsit.org
  9426.  
  9427.                        -------------------------------
  9428.  
  9429. 21. Acknowledgements
  9430.  
  9431. A jolly little song that explains how to solve commonly-encountered problems
  9432. in Java.
  9433.  
  9434.                     The FAQ Melody
  9435.                   by Antranig Basman.
  9436.  
  9437. On the First Day of Christmas, my true-love said to me:
  9438. Read the F-A-Q.
  9439.  
  9440. On the Second Day of Christmas, my true-love said to me:
  9441. My Image isn't drawing;
  9442. Read the F-A-Q.
  9443.  
  9444. On the Third Day of Christmas, my true-love said to me:
  9445. My Pixels are not grabbing,
  9446. My Image isn't drawing,
  9447. Read the F-A-Q.
  9448.  
  9449. On the Fourth Day of Christmas, my true-love said to me:
  9450. My Layout is not laying,
  9451. Pixels are not grabbing,
  9452. Image isn't drawing,
  9453. Read the F-A-Q.
  9454.  
  9455. On the Fifth Day of Christmas, my true-love said to me:
  9456. Null - Pointer - Exception!
  9457. My Layout is not laying,
  9458. Pixels are not grabbing,
  9459. Image isn't drawing,
  9460. Read the F-A-Q.
  9461.  
  9462. On the Sixth Day of Christmas, my true-love said to me:
  9463. Netscape will not run it,
  9464. Null - Pointer - Exception!
  9465. Layout is not laying,
  9466. Pixels are not grabbing,
  9467. Image isn't drawing,
  9468. Read the F-A-Q.
  9469.  
  9470. On the Seventh Day of Christmas, my true-love said to me:
  9471. J++ don't mind it,
  9472. Netscape will not run it,
  9473. Null - Pointer - Exception!
  9474. Layout is not laying,
  9475. Pixels are not grabbing,
  9476. Image isn't drawing,
  9477. Read the F-A-Q.
  9478.  
  9479. On the Eighth Day of Christmas, my true-love said to me:
  9480. Threads they are a-blocking,
  9481. J++ don't mind it,
  9482. Netscape will not run it,
  9483. Null - Pointer - Exception!
  9484. Layout is not laying,
  9485. Pixels are not grabbing,
  9486. Image isn't drawing,
  9487. Read the F-A-Q.
  9488.  
  9489. On the Ninth Day of Christmas, my true-love said to me:
  9490. Dialogs-a-hanging,
  9491. Threads they are a-blocking,
  9492. J++ don't mind it,
  9493. Netscape will not run it,
  9494. Null - Pointer - Exception!
  9495. Layout is not laying,
  9496. Pixels are not grabbing,
  9497. Image isn't drawing,
  9498. Read the F-A-Q.
  9499.  
  9500. On the Tenth Day of Christmas, my true-love said to me:
  9501. Time-zone's in Pacific,
  9502. Dialogs-a-hanging,
  9503. Threads they are a-blocking,
  9504. J++ don't mind it,
  9505. Netscape will not run it,
  9506. Null - Pointer - Exception!
  9507. Layout is not laying,
  9508. Pixels are not grabbing,
  9509. Image isn't drawing,
  9510. Read the F-A-Q.
  9511.  
  9512. On the Eleventh Day of Christmas, my true-love said to me:
  9513. Docs are not specific,
  9514. Time-zone's in Pacific,
  9515. Dialogs-a-hanging,
  9516. Threads they are a-blocking,
  9517. J++ don't mind it,
  9518. Netscape will not run it,
  9519. Null - Pointer - Exception!
  9520. Layout is not laying,
  9521. Pixels are not grabbing,
  9522. Image isn't drawing,
  9523. Read the F-A-Q.
  9524.  
  9525. On the Twelfth Day of Christmas, my true-love said to me:
  9526. File I/O's horrific,
  9527. Docs are not specific,
  9528. Time-zone's in Pacific,
  9529. Dialogs-a-hanging,
  9530. Threads they are a-blocking,
  9531. J++ don't mind it,
  9532. Netscape will not run it,
  9533. Null - Pointer - Exception!
  9534. Layout is not laying,
  9535. Pixels are not grabbing,
  9536. Image isn't drawing;
  9537.  
  9538. You Should Read The-e F-A-Q!
  9539.  
  9540. FAQ copyright 1997, 1998, 1999 by Peter van der Linden. Contributions and
  9541. help from:
  9542.  
  9543. Matt Kennel, Patric Jonsson, Brad Van Tighem, Tony Hursh, Glenn L
  9544. Vanderburg, Peter Jones, John McDowall, Jim Driscoll, Uday, Dave Harris,
  9545. Bill Wilkinson, Tom Valesky, Dan Drake, Giles Thomas, Mitch Baltuch, Guy
  9546. Ruth Hammond, Gordon Keith, Jason Brome, Shani Kerr, Steve Chapel, Timothy
  9547. Wolters, Robert Lynch, Jake Cormier, Sean C Sullivan, Joseph A. Millar, Jim
  9548. Frost, Jim Balter, Jeff Bauer, John Kochmar, Carl Burke, William Stubbs,
  9549. Mark Smith, Volker Turau, Real Gagnon, Russell Gold, Max Hailperin, Bill
  9550. Tschumy, Marco Nijdam, Marc Pawlowsky, Laurence Vanhelsuwe, Ian Macgregor,
  9551. Mike Faulkner, Rich Koch, Will Clark, Govind Seshadri, Rich Simkin, Ian
  9552. Stiles, Kieren, Darren Christie, Tom Lane, Michael Jungmann, Rob Mayoff,
  9553. George Ruban, Tom McCann, David Hopwood, Thomas Phan, Kai Stuke, Rolf
  9554. Howarth, Derek Snider, David Boydston, Andy Godwin, John F. Dumas, Doug
  9555. Bell, David J. Biesack, Tiger Quimpo, Martin Hugh Rogers, Brian Krahmer, Ian
  9556. Burrell, Nikki Locke, Bin Li, Jackson Thompson, Steve Odendahl, Greg Smith,
  9557. Jeffrey C. Ollie, Mark Halvin, Jeremy Cook, Lak Ming Lam, Peter S. Morris,
  9558. Mark Halvin, Juergen Keil, Alex Stewart, Mike Abney, Rodney Stephenson, Mark
  9559. Gritter, Satish Talim, Tamminen Eero, Alexander Gridnev, Eric Hodges, Jamey
  9560. Graham, Will Lockhart, Scott Plante, Tom Sanfilippo, Jan Newmarch, Sean
  9561. Breslin, Stuart D. Gathman, rhino@wwdc.com, C Matthew Curtin, Tor Iver
  9562. Wilhelmsen, A.N.Pryke, Phil Race, David Holmes, David Rodal, Dominique
  9563. Plante, Trent Jarvi, Ingrid Biery, Gopal Unni Krishnan, Grant Lewis, Tov Are
  9564. Jacobsen, Gary McGath, Marty Hall, Will Forster, Colin Mummery, Darin
  9565. McBride, Mayank Shah, Jens Alfke, Glen Stampoultzis, Philip Brown, Peter
  9566. Steiner, Kurt Spaugh, Rasmus Ekman, Jonathan Revusky, Ken Kalish, Dave
  9567. Sanders, Bill Hyden, James Cloughley, Philip "diodes" Gustafson, Paul
  9568. Kinnucan, Juan ValdΘz, Antranig Basman, Felix Pahl, David N. Still, Simon
  9569. Arthur, Mark Hammond, Dan Kegel, Thomas Weidenfeller, Pavel Shvartsman,
  9570. Christen Monberg, George Reese, Ian Macgregor, John Sublett, David
  9571. Zimmerman, Tony Dahlman, Druid, Chris Kelly, Patricia Shanahan, Paul Hill,
  9572. Lyne Lamoureux, Don Kennedy, Alec Muffett, Andrew Mickish, Pavel Shvartsman,
  9573. Neil of Parkway Consultants, Chris Thiessen, David Michaels, Bob Sutherland,
  9574. Michael Allen Latta, Joshy, Eric Albert, Wes Isberg, Lisa Retief, Michael
  9575. Park, Dave Postill, Thomas Weidenfeller, Konstantin Laufer, Hσkan
  9576. Gustavsson, James Stauffer, Reuben Firmin, David Lim, Eamonn Maher, Craig
  9577. West, Pavel Shvartsman, Jay Dunning, Kevin Swan, Grant Gainey, Dan Schmitt,
  9578. Benjamin Goldberger, Jake Hamby, Yaakov Itzhaki, Robert Lynch, Laura Werner,
  9579. Tomm Hoeft, King Dale, Joe Halpin, Daniel M. Pomerantz, Kevin Kelley,
  9580. misnomer@earthling.net, Peter Seibel, Werner Zsolt, Hank Stuck, David M.
  9581. Karr, John J. Bartholdi, III, Garry Turkington, John Bokma, Frank McCreedy,
  9582. Nat Pryce, Jeff Luszcz, Brent Callaghan, Neil Allen, Joe Preston, Tim Bell,
  9583. Rajesh, Jeffrey Galyan, Nick Matsakis, Larry Hamel, David Lamb, Mr Tines,
  9584. Bill McHardy, Phillip Lord, Jon K. Hellan
  9585.  
  9586. ------------------------------------------------------------------------
  9587.  
  9588. I am maintaining a FAQ list to address specifically programming issues
  9589. (not a general tutorial on Java). Please mail suggested FAQ entries
  9590. including answer to faqidea on the site afu.com.
  9591. Question with answer gets you a credit in the FAQ.
  9592. Peter van der Linden, Sun Certified Java Programmer.
  9593. ------------------------------------------------------------------------
  9594.  
  9595. Cross references
  9596.  
  9597. Most cross reference links inside this document are still to be filled in
  9598. after the great FAQ re-org. If you'd like to contribute a few, send me the
  9599. new text for the NAME= and the HREF=, and I'll fold them in as time permits.
  9600. Look at the FAQ source for the style to follow.
  9601.  
  9602. Copyright
  9603.  
  9604. Copyright (c), 1997,1998,1999 Peter van der Linden. Permission to copy all
  9605. or part of this work is granted for individual use, and for copies within a
  9606. scholastic or academic setting. Copies may not be made or distributed for
  9607. resale. The no warranty, and copyright notice must be retained verbatim and
  9608. be displayed conspicuously. You need written authorization before you can
  9609. include this FAQ in a book and/or a CDROM archive, and/or make a
  9610. translation, and/or publish/mirror on a website (scholastic and academic use
  9611. excepted). If anyone needs other permissions that aren't covered by the
  9612. above, please contact the author.
  9613.  
  9614. No Warranty
  9615.  
  9616. This work is provided on an "as is" basis. The copyright holder makes no
  9617. warranty whatsoever, either express or implied, regarding the work,
  9618. including warranties with respect to merchantability or fitness for any
  9619. purpose. Furthermore the author has been known to wear socks that don't
  9620. match his pants, and to commit other egregious lapses of good fashion sense.
  9621.  
  9622. ------------------------------------------------------------------------
  9623.