Click here for a more up-to-date HTML version.
(That link will probably just send you here.)
Frequently Asked Questions (with answers) for Java programmers

           _____________________________________________________
  ________|                                                     |________
  \       |   Java Programmers FAQ         http://www.afu.com   |       /
   \      |   Last modified Jan 13, 1999   Peter van der Linden |      /
   /      |_____________________________________________________|      \
  /___________)                                              (__________\

The Java FAQs here are intended for people who already have some programming
experience, though maybe not in Java.

Go to the FAQ home page at http://www.afu.com for other Java information and
downloads, and the most up-to-date copy of the FAQ. Report FAQ updates to
faqidea at the address afu.com.

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

Specify standard Java on your new PC!

        Your new PC can come with the most up-to-date standard version of
        Java, but only if you ask for it! The JavaLobby is asking PC vendors
to support Java, and to ship new machines with the Java Plug-In
pre-installed.

See http://www.javalobby.org/servlet/PetitionServlet/pjpc
Please help the Java Lobby to promote this initiative.

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

Please support Java Portability.

The biggest value of Java is its portability.

   * Portability makes it easier for companies to change/upgrade operating
     systems and platforms, without losing their investment in applications
     software.
   * Portability makes it easier for Java programmers to transfer their
     skills to new employers.
   * Portability makes a wider variety of software available on all
     computers.

Software portability is very much in the interest of most software
developers and customers. Even if you only use Windows 95, portability
matters to you. If your software was all written in Java, it would all just
run when you moved from MS-DOS to Windows 3.1 to Windows 95 to Windows 98 to
Windows NT, and even on Windows CE. Instead, you typically need to buy new
applications software all over again when Windows changes. Portability is
not in Microsoft's interest, as it removes a revenue stream and makes it
easy for users to try other operating systems.

The 1998 anti-monopoly case against Microsoft revealed a Microsoft internal
memo. The memo stated that Microsoft's "strategic objective" was to "kill
cross-platform Java." by grow[ing] the polluted Java market." This is
Exhibit 101 (MS7 033448) in the case.

In November 1998, a Federal judge ruled that Microsoft was probably breaking
its written agreement with Sun by distributing incompatible Java, and that
Microsoft had to stop doing that. If portability matters to you or your
users, avoid Java products from Microsoft; it is deliberately undermining
it. See http://www.usdoj.gov/atr/cases/f1700/1762.htm.

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

The sections of the Java FAQ are:

   * Portability
   * 1. Java Book Information
   * 2. General Information
   * 3. Compilers and Tools
   * 4. Getting Started
   * 5. Compiler Messages
   * 6. Java Language issues
   * 7. I/O
   * 8. Core library issues
   * 9. Computer Dating
   * 10. AWT
   * 11. Swing
   * 12. Browsers
   * 13. Applets
   * 14. Multi-Media
   * 15. Networking
   * 16. Security
   * 17. For C, C++ Afficionados
   * 18. Java Idioms
   * 19. Java Gotcha's
   * 20. Further Resources
   * 21. Acknowledgements

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

1. Java Book Information

  1. (sect. 1) Learning Java

     [*] The Java FAQ is maintained as a service to the Java community. Java
     is a great language, and everyone benefits when newcomers get a helping
     hand.
     Please consider these books from the FAQ author when you are looking
     for a programming text.
        o "Just Java 1.2" Java, for people who can already program in
          another language.
          More at
          http://www.amazon.com/exec/obidos/ASIN/0130105341/qid%3D912557197/002-7338022-7872449

          Comments from a reader: "Just Java is a great book! Before I
          bought it, I had a couple of other books that were OK, but I kept
          going back to the bookstore to check "Just Java" whenever some
          aspect of the language was unclear. Invariably the Just Java
          explanations were lucid and to the point. I just had to get it."

        o "Not Just Java, 2nd Edition" Java explained for managers and the
          rest of us. More info at
          http://www.amazon.com/exec/obidos/ISBN=0138646384
          Comment from readers: "...An excellent overview of the IT maze"
          "... Not Just Java lets readers educate themselves on where we
          are, and where we're going."
          "This book describes, with graphical illustrations, the emerging
          new ideas and how to use them."

     Sample chapters are on Sun Microsystems' webpage at
     http://www.sun.com/971124/cover-linden/.

  2. (sect. 1) How do I choose a Java book?

     [*] There is no one right answer to "which is the right Java book for
     me?" It all depends on what you already know and how you like to learn.
     Here are the points to check when evaluating a programming book.
        o Above all, make sure that it is a Java book. If it comes with a
          CD, check that it has a Java compiler on it, not a J++ compiler.
          J++ is a different language in some small but important ways, and
          is missing several of the key Java libraries.
          If your interest is Java, leave the J++ book back on the shelf.
        o Does the book cover the current level of Java, which is Java 1.2
          (aka Java 2)? Look up "JApplet" in the index. If it's not there
          the book doesn't cover JDK 1.2, and you probably need a more
          up-to-date book.
        o Check that the book has a reasonable number of figures, diagrams,
          and illustrations. It is not possible to explain how to program a
          window system without pictures and diagrams. Other topics benefit
          from pictures, too.
        o Check what the book says about itself. Is it a reference work,
          intended for Java-experts to look things up in? This is the role
          of "Java in a Nutshell", and "The Java Almanac". Do you need that,
          or are you looking for a book that teaches by examples and
          explanations?
        o Programming is one of those things that you learn by doing. Check
          that each chapter has exercises, preferably with answers. You'll
          need to do the exercises to learn the language. Read Peter
          Norvig's excellent advice on learning programming languages and
          being a programmer.
        o Appraise your own level of programming knowledge: are you
          proficient in some other language, or are you learning programming
          as well? Does the book cater to your needs?
        o Read a section of the book. Does the style keep you interested, as
          it educates you? Will you get bored if you read many pages? Is the
          book too long for your initial purpose? Browse Amazon online and
          see what other readers say about the text.
        o If the book comes with a CD, how much other software is on the CD?
          You want at least a Java compiler plus all the examples from the
          book. Does the Java compiler work on your platform (Mac, Linux,
          etc)? Additional software on the CD is a big plus, as we learn the
          most from reading other people's code.
     Probably no one book is perfect for anyone. Most people buy one to
     begin with, then four or five more as they wish to learn more, and
     about more up-to-date topics. The FAQ author has purchased and read
     probably 60 Java books in the last three years.

  3. (sect. 1) Where can I find a some lists of Java books and book reviews?

     [*] Here are some good ones:
     http://www.flathill.com/languages/java/
     also
     http://www.fastgraph.com/books/java.html
     also
     http://teamjava.com/links/tj-srv.cgi?MUF=0,tj-booklist.muf
     also
     http://www.javaworld.com/javaworld/books/jw-books-index.html
     (an exhaustive list -- takes a long time to load).

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

2. General Information

  1. (Sect. 2) Is Java "Open" or "Proprietary"?

     [*] The Java specification is publicly available, and anyone is free to
     do clean-room implementations of the JVM and core Java API's. Sun
     includes a perpetual, irrevocable, free and royalty-free license in the
     front of the Addison-Wesley books containing the specification.

     Sun also provides free access to the Java source. If you aren't
     planning on using the results in a commercial product, or doing any
     sort of external redistribution, there is an Internal Noncommercial Use
     Source License available at no charge. Please see
     http://java.sun.com/nav/business/source_form.html

     Using the Java trademark does requires licensing from Sun. It is not
     clear if the Embedded or Personal Java specifications are open, as it
     is not clear if a clean-room implementation may be done without
     licensing from Sun.

     The relative openness of Java contrasts with systems that are only
     available from one vendor, whose interfaces are developed in secret,
     without an open process for others to participate, whose owners do not
     allow competing implementations of the same API, and whose owners
     change the APIs as a strategic weapon against competitors. Typically,
     such systems also feature "private" APIs that are published late or not
     published at all, to allow the single vendor to gain a competitive
     advantage for their other products. Typically such proprietary systems
     do not make the source code available for inspection by all.

  2. (Sect. 2) What is the best way to refer someone to the FAQ when they
     ask a question I know is answered there?

     [*] The Java Programmers FAQ (at http://www.afu.com) answers your
     question in section N.n. ...

     This gives them the answer, and shows them where to go for future
     questions. It also demonstrates that the FAQ can answer their
     questions, supplying an incentive to go there next time. It's regarded
     as elementary politeness to look for the FAQ of a newsgroup and read it
     before posting any questions.

     In general, FAQs for any newsgroup are available by looking at past
     postings in a group, or by searching Deja News (see Q 1.4), or via
     anonymous FTP at directories under ftp://rtfm.mit.edu. The pathnames
     are called things like
     /pub/usenet-by-group/comp.lang.java.programmer/Java_Programmers_FAQ
     which may help you get to the right one directly, as it takes some time
     to get a directory listing there. Alternatively, you can look for
     newsgroup names on the same ftp site by going to the same site and
     looking under /pub/usenet-by-hierarchy/. That has subdirectories such
     as alt/, ba/, ca/, comp/, and subdirectories under them such as
     /pub/usenet-by-hierarchy/comp/lang/ and so on. This helps you explore
     the world of newsgroups with FAQs.

     If you do not have anonymous FTP access, you can access the
     rtfm.mit.edu archives by mail server as well. Send an E-mail message to
     mail-server@rtfm.mit.edu with "help" in the body for more information.
     "RTFM" stands for "Read The effing Manual" - you must expect to put in
     some time and effort to master a new area of study.

     If you want to look at the definition of Internet standards like FTP,
     telnet, visit the IETF site at http://www.ietf.org where all the RFC's
     (Request For Comments) can be found.

  3. (Sect. 2) What if my question is not answered in this FAQ?

     [*] Go to http://www.dejanews.com/home_ps.shtml
        o Under "Newsgroups" enter "comp.lang.java.programmer" (or whatever)
        o Under "Subject" enter "Frotteur" (or other topic you find
          pressing)
        o Click "Create Filter"
        o It will go to a new document, and you should click the link
          labeled

          nnn Documents (nnn is some number).

     The chances are that you will find several answers to your question.
     Some may not be complete or completely accurate however. That is the
     nature of Usenet, and free information. If you still don't have an
     answer, then post your question on the most appropriate of the
     newsgroups. Don't spam the newsgroups by posting to multiple groups.
     Knowledgeable posters tend to ignore questions like that.

     Also look at http://sunsite.unc.edu/java/cgi-bin/query
     and look at http://asknpac.npac.syr.edu/ for a Java newsgroup search.

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

  4. (Sect. 2) What Java mailing lists are there?

     [*] There are quite a few Java mailing lists.
     http://java.miningco.com/msub7.htm has a comprehensive list.

  5. (Sect. 2) Where can I look at the definitive Java Language
     Specification?

     [*] This is available online at:
          http://java.sun.com/docs/books/jls/html/index.html (Java 1.0)

     and the Java 1.1 inner classes document at:
          http://java.sun.com/products/jdk/1.1/docs/guide/innerclasses/
          spec/innerclasses.doc.html

     and the other Java 1.1 update at:
          http://java.sun.com/docs/books/jls/html/1.1Update.html

     and the Java API is at:
          http://java.sun.com/products/jdk/1.1/docs/api

     It is also available as a book in printed form (details at website).
     Also see the "Clarifications and Amendments"
     http://java.sun.com/docs/books/jls/clarify.html.

     You can also see the virtual machine (execution environment)
     specification at
     http://docs.sun.com:80/ab2/coll.127.1/@Ab2CollToc?subject=java

  6. (Sect. 2) Where can I find information about future Java APIs?

     [*] JavaSoft has followed a policy of creating new APIs in consultation
     with leading industry participants, then posting the draft
     specification for public review and comments. Check the JavaSoft
     roadmap of new APIs and products at
     http://java.sun.com:80/products/api-overview/index.html
     Also, some APIs that are under consideration, possibly for JDK 1.2 are
     at:
          http://java.sun.com/products/jdk/preview/docs/

  7. (Sect. 2) I'm looking for a Java style guide on naming conventions.

     [*] Check out the section "Naming Conventions" in the language
     specification
          http://java.sun.com/docs/books/jls/html/6.doc.html#11186

     Also take a look at Doug Lea's draft coding standard -
          http://gee.cs.oswego.edu/dl/html/javaCodingStd.html

     See also naming conventions for some basic rules of thumb.

  8. (Sect. 2) How do I check on known bugs in the JDK?

     [*] Look at the Java Developer Connection at http://java.sun.com/jdc.

     All the Java bugs that Sun knows about are listed there, with the
     exception of security-related bugs. The legal department in Sun vetoed
     the open publication of security bugs. After you have checked that the
     bug is not already listed, you can submit a bug report through:
     http://java.sun.com:80/cgi-bin/bugreport.cgi
     You should check that the bug doesn't already exist for two reasons:
     first, you might find the bug with a workaround listed. Second, you
     don't want to waste everyone's time with a duplicate bug report.

     You can also send in an RFE (Request For Enhancement) or ease-of-use
     issue there. You can even vote on the priority you would assign to a
     particular bug fix! Join the Java Developer Connection (it's free) by
     going to http://java.sun.com/jdc. Then browse
     http://developer.javasoft.com/developer/bugParade/#votes

  9. (Sect. 2) What computers have Java ports? Is there a port to Win 3.1?

     [*] A partial list of JDK ports is available from
     http://java.sun.com/cgi-bin/java-ports.cgi
     An (impressive) list of the systems that the GPL Kaffee JVM runs on is
     at http://www.transvirtual.com/ports.html

     There are several Java ports to Win 3.1. IBM's ADK1.02 is available at
     the following locations:
        o http://ncc.hursley.ibm.com/javainfo/latest/answers/faq0.html
        o http://www.alphaworks.ibm.com/formula
     IBM offers a port to Linux, as do others. The IBM Jikes port is at
     http://www.alphaworks.ibm.com/ There is a large amount of useful
     software there, including a profiling tool called jinsight.

     Netscape Navigator for Win3.1 has Java support. Java will never be
     well-supported under Win3.1 because Win3.1 lacks the basic features
     expected of a modern OS (primarily lengthy filenames and multithreading
     support).

     Also take a look at JavaSoft's JavaPC kit that can switch a PC into a
     thin client Java system (and back to Win3.1/DOS when you want). It's
     meant for software OEMs and large corporations running lots of older
     PCs, but you can use it on the latest Pentium II too. Details are at
     http://java.sun.com/products/javapc/index.html. JavaPC is available now
     for $100, runs on 486's with 8Mb or more Unlike the 16-bit versions of
     Netscape Navigator and Microsoft Internet Explorer, which provide a
     Java Virtual Machine that is only compliant with the JDK 1.0.2 API, the
     JavaPC software allows IS managers to deploy JDK 1.1-compatible Java
     applications on PCs running DOS and Windows 3.x.

 10. (Sect. 2) Where can I find information on Java 3D?

     [*] The Java 3D FAQ at http://tintoy.ncsa.uiuc.edu/~srp/java3d/faq.html
     may have the answers you're looking for. It contains general
     information about Java 3D, as well as programming tips.

 11. (Sect. 2) Where can I find information about Java Certification?

     [*] Sun is sponsoring an examination which programmers worldwide can
     take. Those passing can use the designation "Sun Certified Java
     Programmer". There is also a second-level test, involving writing a
     program to spec, and taking a further test. That results in the
     qualification "Sun Certified Java Developer". You can find out all
     about the exam at:
          http://www.sun.com/service/suned/

     and then search for "sun certified java". It costs $150 to sit the Java
     Programmer exam. It is not trivial to pass the Java certification exam.
     It requires understanding the objectives of the test, and the material
     that is tested for. These are given, along with sample questions, at
     the URL mentioned above.

     There is a Java certification FAQ at: http://www.marcusgreen.co.uk

 12. (Sect. 2) How can I find links to recent news about Java?

     [*] This site contains links to late-breaking online news stories about
     Java. http://www.intelligence.com/java/
     Another good Java news source is http://www.nikos.com/javatoys.

     This site is a fine site for programmers who want to be well-informed
     about computer industry topics. It has a lot of coverage of Linux as
     well as more general news. http://slashdot.org Highly recommended.

     This site is a source of independent news and commentary on the
     computer industry, including Java. http://www.pjprimer.com/media.html.
     You have to subscribe ($10/year, 30 day free trial).

 13. (Sect. 2) What are the folks at GNU doing with Java?

     [*] First note that the URLs in this section change quickly, and soon
     become outdated. If you have an update, send it in. There is a Gnu Java
     page at http://www.gnu.org/software/java/java.html
     Guava (a GPL'd Java compiler) can be found at
          ftp://ftp.yggdrasil.com/pub/dist/devel/compilers/guavac/
     Alternatively, it may be available at
     http://http.cs.berkeley.edu/~engberg/guavac
     Work is progressing on the Cygnus Java frontend to gcc. See
     http://www.cygnus.com/product/javalang/

     Kaffe (a JVM) can be found at
          http://www.transvirtual.com This is Tim Wilkenson's company
          devoted to commercializing the Kaffe JVM for the embedded systems
          market. He also releases a version of it under the GPL. It also
          comes with a the beginnings of a class library and the Pizza
          compiler.

     Classpath is a free implementation of Sun's core Java libraries (v1.1),
     being developed for the GNU Project ( http://www.gnu.org). Information
     regarding classpath is at http://www.classpath.org They aim to develop
     a 100% free drop in replacement for Sun's class libraries, targeting
     first the Japhar JVM (below). They are always looking for help, so feel
     free to stop by and volunteer.

     See also http://www.japhar.org This is the Hungry Programmer's JVM.
     Currently it is development grade only.

 14. (Sect. 2) What is "San Francisco"?

     [*] San Francisco is the code name for a very large Java project led by
     IBM, and involving other companies. The project is to provide a Java
     framework for data processing applications. A large number of classes
     are provided for general ledger, sales order, inventory management,
     etc., and these classes can be extended and customized for particular
     industries (vertical markets). It is a large and ambitious software
     project.

     IBM's SF project competes with products from companies like SAP and
     Baan. Of course, the SF project is multi-platform and uses Java beans
     and GUI interfaces. More information on SF is available at
     http://www.ibm.com/Java/Sanfrancisco

 15. (Sect. 2) What large Office-style or other applications have been
     written in Java?

     [*] Well, the first one to consider is IBM's San Francisco project,
     mentioned above. There is also Lotus's e-suite - a suite of Java
     applets and beans including a spreadsheet and a word processor. See
     http://esuite.lotus.com. These became available in March 1998.

     Another office suite in Java is Applix Anyware at
     http://www.applix.com/anyware/index.htm. Applix became available in
     downloadable demo form in April 1998.

     Yet another is Star Division's Client/Server Office. It is an office
     suite with the client part written in Java and able to run on
     JavaStations. The server part will run on Solaris, NT, OS/390, and
     AS/400. The older (non-Java) version is bundled with all Sun
     workstations sold in Germany. The Linux version is freely downloadable
     from http://www.stardivision.com.

     Another is Digital Harbor's Wav word processor. It supports component
     software, and it runs in 1MB, not the 114Mb of the latest MS Word. A
     free trial is avilable. See: http://www.digitalharbor.com

     Another Java application is Formula One for Java, an Excel-compatible
     spreadsheet written in 100% pure Java, and available for all systems
     that support Java. It runs as a Java Bean, so can easily be assembled
     as one component of a larger system. It also runs as an application,
     and as an applet! Formula One is a product of Visual Components, Inc.
     See http://www.f1j.com.

     Another one is Ncode Research Inc. who write Java viewers for office
     suites. They are file-format specialists. Their mission is to make all
     popular file formats available for the Java platform. They write 100%
     Pure Java viewers for Word, Excel and PowerPoint (including Office 95
     and 97 formats). See http://www.ncode.com/
     Another company operating in the same space is JSoft, at
     http://www.jsoftinc.com

     The niche for single-user office productivity applications is pretty
     well already dominated by Microsoft products, and it is unrealistic to
     think that Java software will unseat shrink-wrapped software simply
     because it is written in Java. This is why Corel replanned its Java
     rewrite of Corel Office before taking it to FCS. When Corel did that,
     it also increased its investment in Java from 33% of R&D budget to 50%,
     at the expense of Windows.

     Most of Java development is taking place for custom applications
     internal to a company. Most programmers of any kind have never worked
     on MS Office, but work on internal applications, and so it is with
     Java. These projects don't have the high profile of major vendors'
     products, but they are the mainstay of the industry. There are many
     companies working on Java Beans, like http://www.quadbase.com who have
     Java graphing software. EspressChart is a Java Bean that gives you the
     ability to add 2D and 3D graphs in your applications/applets. This bean
     is easy to use, 100% Java, and runs anywhere.

     There are some good Java games applets at
     http://www.frontiernet.net/~imaging/java_games.html
     If you want to use Java to learn math & computer graphics, visit
     http://www.frontiernet.net/~imaging/math_is_a_game.html

     Finally, note that Sun's Java compiler is written in Java. This is a
     really big application in widespread use on millions of platforms. The
     compile command "javac test.java" is equivalent to

         java sun.tools.javac.Main test.java


     javac has a script wrapper just to set the heap size as a command line
     argument, as you can do in your own programs.

 16. (Sect 2.) What Java User Groups are there?

     [*] There are scores of Java User groups around the world, mostly in
     urban areas, and centers of software technology development. A partial
     list with contact information can be found at
     http://sunsite.unc.edu/javafaq/usergroups.html.

     If you can't find a user group in your area/school, it's easy and
     satisfying to start one.

 17. (Sect 2.) What is a Java Bean?

     [*] A Java bean is a Java class that follows some simple conventions.
     Because it follows conventions, it can easily be processed by a
     software tool that connects Beans together. Java beans are reusable
     software components.

     Think of Java beans as being the software equivalent of Lego[tm]
     bricks. Instead of plugging together plastic bricks, you can easily
     plug together classes, and have them fit and work with each other. See
     http://www.jc100.org/
     See the Java Bean FAQ at http://java.sun.com/beans/faq/faq.general.html

 18. (Sect 2.) Where can I find examples of the use of the Java class
     libraries?

     [*] The two volumes of "Java Class Libraries" by Chan, Lee and Krama
     published by Addison Wesley, have extensive examples of how to use the
     standard libraries. One programmer comments "When I need to use an
     unfamiliar area of the class libraries one of the first things I do is
     read their examples." You can see them online at
     http://java.sun.com/docs/books/chanlee/second_edition/vol1/examples.html
     and http://java.sun.com/docs/books/chanlee/second_edition/examples.html

 19. (Sect 2.) How can I find out exactly what version of Java I have on my
     system?

     [*] On a Solaris system, you can use the pkginfo command, like this:

        pkginfo -l SUNWjvrt

     It will give a reply like this:

        PKGINST:  SUNWjvrt
           NAME:  JavaVM run time environment
       CATEGORY:  system
           ARCH:  sparc
        VERSION:  1.1.6,REV=1998.07.30.16.21
        BASEDIR:  /
         VENDOR:  Sun Microsystems, Inc.
      ...etc

     You may also try

        java -fullversion

     Although that's not an officially-supported command option, and has
     gone away in JDK 1.2. Try also

        java -version

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

3. Compilers and Tools

  1. (Sect. 3) Is there a lex and yacc or preferably a flex and bison
     equivalent for Java?

     [*] There is a lex equivalent called JavaLex and a yacc equivalent
     called CUP.

     LALR(1) parser JavaLex and JavaCup:
     http://www.cs.princeton.edu/~appel/modern/java/

     LL(k) parser JavaCC: http://www.suntest.com/JavaCC/
     LALR(1) parser SableCC from McGill U.
     http://www.sable.mcgill.ca/sablecc/index.html is generously made
     available under GNU license.

  2. (Sect. 3) Where can I find a byte code obfuscator?

     [*] There is a commercially supported obfuscator, with a downloadable
     free trial at http://www.4thpass.com/SourceGuard. There are also some
     free works from students and others. http://www.primenet.com/~ej/
     http://www.math.gatech.edu/~mladue/HoseMocha.java

     Some people have reported problems using these with JDK 1.1.

     This obfuscator has been updated to be fully compatible with JDK 1.1:
     http://www.monmouth.com/~neil/Obfuscate.html

     Obfuscators are intended to foil decompilers. Decompilers translate
     byte code back into Java source code. Mocha was the first and most well
     known of the decompilers; it's no longer supported. There is a
     decompiler (written in C++) at
          http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
     Because it is in C++, there are different versions for every
     architecture (hah!) There are also commercial products, such as
     SourceAgain from
          http://www.ahpah.com/

     There's a very good Java Code Engineering and Reverse Engineering FAQ
     page at http://Meurrens.ML.org/ip-Links/Java/codeEngineering/.

  3. (Sect. 3) Which program is used to create .zip files compatible with
     the java* programs?
     (e.g. classes.zip, moz3_0.zip)

     [*] Use the jar-tool from JDK1.1(.1):
          jar [ options ] [manifest] destination input-file [input-files]

     E.g.:
          jar cvf myJarFile.jar *.class

     creates a compressed archive
          jar cvfO myJarFile.zip *.class

     creates it fullsize (uncompressed) (note the 'O'-option used for
     JDK1.0.2)

     On Unix you can also use:
          zip -rn ".class" my_file.zip *

     Info-ZIP home page: http://www.cdrom.com/pub/infozip/
     Latest source code: ftp://ftp.uu.net/pub/archiving/zip/src/zip21.zip

     Netscape's command line version of its JAR packager and signing tool is
     called "zigbert". They also have a signing tool with GUI written in
     Java. More info
     http://developer.netscape.com/software/signedobj/jarpack.html

     If you zip your .class files for JDK 1.0.2 (for 1.1 you'll use a Jar):
       1. zip your files uncompressed (can use WinZip 6.2 up);
               Unix command:

               zip -r0 classes.zip 

       2. Make sure the main class has no parent directory inside the
          archive, (in other words, don't build an archive with
          foo/bar/myMain.class, unless your myMain is in a package called
          foo.bar. Instead start it at myMain.class). Your packages must be
          placed in the archive using their corresponding filesystem
          pathnames.
       3. Put the archive in the same directory as the .html page.
       4. Put something like the following tag in the .html file:

          
              


     From JDK 1.1 on, an example of the applet tag used with a jar file is

     
             


     These lines will use an applet called myapplet that can be found in the
     jarfile myfile.jar. An example applet tag of a jar file used to hold
     classes in packages is

     
             


     You can supply several jar filenames in a comma-separated list. Jar
     files are in compressed PKZIP format.

  4. (Sect. 3) Can I compile a Java program to a binary executable, .exe on
     a PC?

     [*] Compiling into native code destroys portability, which is one of
     the main benefits of Java. If you want to create a native executable
     because you wanted to make it easy to distribute and use programs,
     consider a Jar file instead.
     Some companies make products that do this. See the webpages for
     Symantec http://www.symantec.com, Supercede http://www.supercede.com,
     and Tower Technology http://www.twr.com. The first two are targeted to
     Windows. Tower Technology supports several flavors of Unix.

     Also, there is a native Java compiler from IBM, known as the HPJ (High
     Performance Java) compiler. One user has reported that it created a 2Mb
     executable from a 12K java file, and did not run any faster. See
     http://www.alphaworks.ibm.com/

     See also Instantiations JOVE http://www.instantiations.com/jove.htm,
     the paper about the Toba project
     http://research.microsoft.com/research/lt/toddpro/papers/coots97.pdf,
     Network World, "Vendors Rush To Speed Java Performance", Feb 9 1998, at
     http://www.nwfusion.com/news/0209java.html

     Compiling to native code takes away the most significant benefit of
     Java: portability of executables. Further, if you want your Java DLL
     (or .exe) to interact with C++, you'll have to specify which specific
     C++ compiler and/or actually compile some sort of linkage via the
     appropriate C++ compiler. C++ does not have a standard ABI, so there is
     a big problem with interoperability. Every C++ compiler uses a
     different object model, a different way of laying out class members,
     and a different way of "mangling" names for the linker.

     C is much simpler. The only question here is how structures are
     "packed" (i.e., are integers aligned on four-byte bounds?). All the C++
     compilers can interact with C code, thanks to 'extern "C"'
     declarations.

     Consider carefully why you want to compile to a native executable, and
     whether there is a Java way to accomplish your goal. There may be a
     good reason for compiling to native code, but it needs to be thought
     through.

  5. (Sect. 3) How can I performance profile my Java code?

     [*]java -prof MyClass

     produces some basic output in a file called java.prof, showing the
     number of times methods were invoked. The output lines are of the form:
          # of calls     method called      called by        time spent
     On a Unix system, you can sort the file with something like

     sort -r +82  java.sort

     More and better Java tools are a third party opportunity. One Java
     profiler is JProbe Profiler, available from http://www.klg.com/jprobe.
     JProbe is said to be easy to use. Another profiler is OptimizeIt,
     available from http://www.optimizeit.com. Each of these profilers has
     performance tuning, which shows which methods took how much time, and
     also memory tuning, which shows what objects are in memory and how they
     were allocated. Both are important things to know. The latest version
     of the CodeWarrior IDE http://www.metrowerks.com has a time-based
     profiler for Java code. Java Workshop from Sun also has a time-based
     profiler.

  6. (Sect. 3) When I use javadoc and I click on any java class included in
     the JDK why do I get this message?

         Netscape is unable to find the file or directory named:
         /E|/Jwrkshop/JDK/bin/java.lang.Throwable.html


     [*] References to the JDK classes assume that all generated html files
     are in the same directory and, in fact, that all files for all classes
     referenced are generated at the same time. There is no way to generate
     files incrementally and have them all reference each other, as you
     would like.

     As long as you have source for everything involved (including the JDK
     and all third-party classes), you can list all of your packages and all
     of the others on the javadoc command line and generate the whole set at
     once, but it is burdensome. Of course, if you receive any libraries as
     .class files, even this workaround will not suffice.

     Also javadoc will not generate the image files - you need to get them
     from the images directory under the JDK API documentation files. You
     can just copy the entire directory into your own doc directory. javadoc
     is a very nice concept, with a few implementation flaws.

  7. (Sect. 3) I'm working on a project with lots of classes and I use the
     JDK. A recompile from scratch takes forever when I do it a class at a
     time. How do I recompile everything?

     [*] The first way is
          javac *.java

     Another way is
          javac -depend tip.java

     where "tip.java" is a class "at the tip of the iceberg", i.e. that
     depends on (uses) all the other classes. Typically, this may be your
     main class. However, "-depend" is known to be buggy and cannot be
     relied upon. It also doesn't issue compile commands in parallel to make
     use of multi-processor systems.

     Without the "-depend" option, the standard "javac files" doesn't look
     beyond the immediately adjacent dependencies to find classes lower down
     the hierarchy where the source has changed.

     The -depend options searches recursively for depending classes and
     recompiles it. This option doesn't help when you have dynamically
     loaded classes whose names cannot be determined by the compiler from
     the dependency graph. E.g. you use something like
          Class.forName(argv[0]);

     The author of the code using those classes should make sure that those
     classes are mentioned in a Makefile.

  8. (Sect. 3) Why do I get the java.lang.UnsatisfiedLinkError when I run my
     Java program containing Native Method invocations?

     [*] Your program is not able to find your shared library or DLL.

     On Windows 95/NT, make sure that the DLL exists in a path that is
     included within the PATH environment variable. (This need is true for
     both standard (untrusted) applications and trusted applets. At least,
     if you use the Java Plug-in to give yourself standard Java inside a
     browser).

     On Solaris, make sure that the environment variable LD_LIBRARY_PATH
     includes the path of your shared library.

  9. (Sect. 3) An anonymous class can't seem to access a private outer
     method. Why is that?

     [*] It's a known bug in the JDK 1.1.4. The code is:

         public class MyDialog {

                 void Setup() {
                 addWindowListener( new WindowAdapter() {
                       public void windowClosing(WindowEvent e) {
                              myCloseWindow(); }
                       }
                       );     // anon inner class
                 }

             private void myCloseWindow() {   // private outer method
                 dispose();
             }
         }

     This code sends javac into an infinite loop. The workaround is to make
     the private method non-private, or to make the inner class a named
     class. Sun put a workaround in the compiler to silently set the field
     to package access.

 10. (Sect. 3) What are the major Java releases and their contents?

     [*] There have been three Java releases from Sun so far, plus a number
     of bugfix (dot-dot) releases. The releases are:
        o JDK 1.0.2
          This was the release FCS in May 1996. It had some security fixes
          over JDK 1.0.
        o JDK 1.1
          This release (Feb 1997) introduced a new event model in the window
          system. It also made JDBC support and beans support a standard
          feature. It changed and standardized the native code interface to
          JNI. It also introduced inner classes.
        o JDK 1.2
          This release (Dec 1998) made the Swing library a standard feature.
          Swing is a set of rich platform-independent graphical components.

 11. (Sect. 3) What is the difference between jre and java?

     [*] They are functionally equivalent, with minor differences in the
     handling of default classpath and options supported. To reduce
     confusion, the jre command was removed in JDK 1.2. Instead there is a
     "java" command in both bin and jre/bin.

     jre.exe is the java launcher that comes with the Java Runtime
     Environment. It ignores the CLASSPATH environment setting in favor of
     its own internally generated default and whatever is supplied on the
     cmd line using -cp or -classpath. It's intended to be a bit simpler for
     those who are only ever running Java programs, not developing them.

     java.exe is the java launcher that comes with the JDK. It uses the
     CLASSPATH environment setting as a starting point and then tacks on its
     own internally generated entries.

     They both serve the same purpose and that's to start a Java VM, have it
     run a Java application, then terminate. The source for jre.exe is
     provided in the JDK. The source to java.exe is provided only in the JDK
     Source distribution.

 12. (Sect. 3) What IDEs (Integrated Development Environments) are there?

     [*] Some popular IDEs include:

      Apptivity 2.0
      (Progress)             http://www.apptivity.com
      Bluette                http://blue.donga.ac.kr/bluette/index.html
      CodeWarrior
      Professional           http://www.metrowerks.com
      GRASP (product is free)http://www.eng.auburn.edu/grasp
      Grinder                http://www.tpex.com
      Java WorkShop 2.0 (Sun)http://www.sun.com/workshop/java
      Javelin, Visual Object
      Development for Java   http://www.stepahead.com.au
      JBuilder (Inprise)     http://www.inprise.com/jbuilder
      JDE for emacs          http://sunsite.auc.dk/jde/
      Kawa (Webcetera)       http://www.tek-tools.com/kawa
      Metamata               http://www.metamata.com
      NetBeans (Swing-based) http://www.netbeans.com
      PARTS alpha
      (ObjectShare)          http://www.objectshare.com
      PowerJ (Sybase)        http://www.sybase.com/products/powerj
      SilverStream           http://www.silverstream.com
      Simplicity for Java    http://www.penumbrasoftware.com
      SuperCede 2.0
      (Asymetrix)            http://www.supercede.com
      teikade 1.8R2 (PFU Ltd)http://www.pfu.co.jp/teikade
      Together/J 2.0 (Object
      Intl Inc.)             http://www.oi.com
      Visaj 1.0.1 (Imperial
      SW Tech)               http://www.imperial-software-tech.co.uk
      VisualAge 1.0 (IBM)    http://www.software.ibm.com/ad/vajava
      Visual Cafe 2.1
      (Symantec)             http://cafe.symantec.com
      Visual J++ (Microsoft) (deliberate incompatiblities; not recommended)
      Xelfi 0.94             http://www.xelfi.com

 13. (Sect. 3) Why is Visual J++ not recommended?

     Because Microsoft's strategic objective is "Kill cross-platform Java"

     [*] It is not in Microsoft's financial interest to allow users to
     easily move software to different platforms. Microsoft is the only
     company in the computer industry that is actively trying to undermine
     Java. This is not speculation -- the Department of Justice's lawsuit
     quoted a Microsoft memo describing the strategic objective to "kill
     cross-platform Java by grow[ing] the polluted Java market". See
     http://www.usdoj.gov/atr/cases/f1700/1762.htm

     Microsoft is being sued because of unauthorized changes it made in
     Java. A federal judge issued a preliminary injunction against Microsoft
     in March 1998, prohibiting them from labelling their incompatible J++
     product as Java. Another injunction was issued against Microsoft in Nov
     1998, requiring them to remove deliberate incompatibilities with
     standard Java. (Recall that Microsoft did not create Java, but
     contracted with Sun to distribute it).

     Speak to your management
     chain - how comfortable do
     they feel using a Microsoft product that is embroiled in a legal
     dispute, that introduces deliberate incompatibilities, and whose stated
     goal is to lock you in to one platform? It is a safer choice to get
     standard Java from any other source than Microsoft. You can use these
     facts to move your company to standard Java.

     As a Java programmer please join the Java Lobby, an independent
     organization dedicated to representing independent non-vendor interests
     in Java. It's free, and you can sign up by visiting
     http://www.javalobby.org for details. Other ways to encourage portable
     java:
        o Use development environments from other vendors, or convert
          Microsoft Visual J++ to use Sun's JDK, following the instructions
          at http://www.orbiter.demon.co.uk/
        o Use Netscape Communicator (not Internet Explorer)
        o If required to use Internet Explorer, use the Java Plug-In to get
          a standard Java system inside it.
        o Use a standard JVM from GNU, Kaffe, any of the IDE vendors, or Sun
          (but not Microsoft's J++ SDK)

        o Free standard Java compilers and the Java Plug-In can be
          downloaded from http://java.sun.com.
        o Free standard Java Virtual Machines can be downloaded from
          http://www.kaffe.org, http://www.oryxsoft.com/projects/gvm, and
          http://www.redhat.com/linux-info/jolt
        o Free Java AWT software can be downloaded from
          http://www.biss-net.com/biss-awt.html and the files are all at
          ftp.java-linux.org (the linux site) too.
        o Free Java software can be downloaded from
          http://www.gnu.org/software/java/java.html

     Just for the record, the May 1998 federal case against Microsoft has
     nothing to do with innovation or product design, as Microsoft
     frequently insists. Microsoft is actually charged with
        o taking anti-competitive action to exclude competition in browsers,
          in order to protect its monopoly in desktop operating systems.
        o using its monopoly to impose restrictive agreements that require
          PC manufacturers to accept the Microsoft browser with Windows, and
          that hinder the promotion of competing browsers.
     Many people think that contracts prohibiting the distribution of a
     third party's products are somewhat sleazy. Such contracts are also in
     restraint of competition and illegal when used by a monopoly. This is
     why Microsoft is facing mounting legal problems in the United States,
     Italy, Brazil, and the European Union.

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

4. Getting Started

     Don't forget to look at the "Compiler Messages" in the next section,
     too.
  1. (Sect. 4) What is the easiest way to get started with Java?

     [*] Follow these steps.
       1. Download a free Java compiler from http://java.sun.com
       2. Read the free Java tutorial, at the same website (bookmark it, so
          you will easily find it again).
       3. Avoid Microsoft's J++ product, which is in the words of
          Microsoft's own employees "polluted Java". It is designed to
          undermine standard Java, and has many deliberate platform-specific
          incompatibilities, including new keywords in the language.
       4. Look at the beginning of this FAQ for book info and book reviews.
          There is no one perfect Java book. The right book depends on the
          style and pace that you are most comfortable with. Amazon has good
          info and reviews on Java books.
       5. Search this FAQ when something in Java confuses you. Many people
          have trodden this path before you, and the FAQ contains the
          accumulated knowledge and pointers to other references.
  2. (Sect. 4) Why doesn't my "Hello World!" program compile?

     [*] There are three basic possibilities:
       1. Are you successfully running the javac compiler?
          Try

          javac -garbage

          to see if it prints out a message about correct usage. If not,
          invoke javac using the full pathname, or set your PATH variable to
          include the directory that contains javac.
       2. Is the CLASSPATH environment variable used correctly?
          In JDK 1.0.2, it was a mistake for beginners not to set CLASSPATH.

          In JDK 1.1, it is a mistake when beginners do set CLASSPATH.
          In JDK 1.2, CLASSPATH is often not needed. You can put your
          classes and Jar files in a directory under the JDK installation,
          which the runtime system always checks.
          When CLASSPATH is wrong, javac will tell you it can't find
          definitions for classes you reference in the source file. For
          information on setting up the CLASSPATH, see Question 4.3
       3. Is the source correct?
          Here javac will emit error and warning messages. See the questions
          on compiler messages in the next section.

  3. (Sect. 4) Why doesn't my "Hello World!" program run?

     [*] There are five common mistakes that cause your VM (java or browser)
     to be unable to execute your classes
       1. First, did you write an applet or an application? If an applet,
          you must make sure that you did extend the java.applet.Applet
          class.
       2. You must declare your main class as "public". If you don't,
          unfortunately some systems will still run the code, while others
          won't. The main class is either the one with the main() method in,
          or in the case of an Applet, the class that extends Applet.
       3. Your class name and the file name must match exactly, even letter
          case. If your class is HelloWorld, your source file must be
          HelloWorld.java and your class file will be "HelloWorld.class".
       4. If an Applet, and you used ftp to transfer the classes to the
          server, you must ftp all the classes, and you must use BINARY
          transfer not ASCII.
       5. Errors in setting the CLASSPATH (and/or codebase in an applet).
          Even seasoned programmers do this, pointing inside a package or
          mistyping a path delimiter. For information on setting up the
          CLASSPATH and codebase, see Question 4.3

     If you are running an applet, you should check the following further
     points:
       1. If your class isn't loading, recheck the HTML applet tag.
       2. If you are writing to System.out, the results are displayed in the
          browser's java console. You'll have to create a window if you want
          one.
       3. Make sure your browser is compatible with the Java language
          features you are using. Internet Explorer and older versions of
          Netscape's browsers have omitted some support for JDK 1.1. Try
          your applet in the JDK's appletviewer first.

  4. How do I set the CLASSPATH?

     [*] The CLASSPATH environment variable tells the VM's class loader
     where to find classes that are directly or indirectly invoked,
     including system classes. The CLASSPATH variable should
        o point to the class directory, for classes not in a package.
        o point to the package root, for classes in a package. The root is
          the parent directory of the highest directory of the package name.
        o point directly to the zip or jar file, if the classes are in an
          archive file. You may have to list the contents of the archive to
          get the correct package/path name for the class.
          Separate multiple paths and archives with a platform-specific
          separator, ";" for Windows; ":" for Solaris
     Also remember that
        o Browsers set the CLASSPATH to the directory of the HTML file, plus
          the codebase parameter.
        o in JDK 1.1 and after, java adds the system classes
          (lib/classes.zip), so you don't have to.
        o most versions of java add "." (current directory), so you don't
          have to. (But jre doesn't - see below.)
        o JDK 1.1 jre tool does not use the CLASSPATH variable or assume the
          current directory. (On Solaris, CLASSPATH does work.)

     From JDK 1.1.2 on, it is generally an error if the user sets the
     CLASSPATH to include classes.zip. But CLASSPATH will need to be set to
        o point to the roots of the programmer's own packages, and third
          party packages
        o use rmic
        o use unbundled packages like Swing in JDK 1.1
        o point to native code libraries.

     If you're not doing any of these, do not set CLASSPATH. If you have set
     it, unset it.
     Below you'll find examples for Windows (basic application class),
     Solaris (package class), javac (multiple packages), and browsers
     (applet codebase).
     -----------------------------

     Here's some Windows examples, assuming the application class is

     D:\src\tries\HelloWorld.class

             ## JDK 1.1,  no CLASSPATH set
             > cd D:\src\tries\
             > D:\jdk11\bin\java HelloWorld
               # OK: 1.1 implicitly adds classes.zip and current dir

             > D:\jdk11\bin\jre HelloWorld
               # FAILS: jre does not automatically add . to CLASSPATH

             > cd D:\
             > D:\jdk11\bin\jre -cp D:\src\tries HelloWorld
               # OK: jre adds classes.zip, -cp adds class directory

             ## JDK 1.1,  CLASSPATH set
             > set CLASSPATH=D:\src\tries
             > D:\jdk11\bin\java HelloWorld
               # OK: java using CLASSPATH

             > D:\jdk11\bin\jre HelloWorld
               # FAILS: jre does not use CLASSPATH (on Windows)

             ## JDK 1.0.2,  CLASSPATH set
             > set CLASSPATH=D:\jdk102\lib\classes.zip;D:\src\tries
             > D:\jdk102\bin\java HelloWorld
               # OK:

             > set CLASSPATH=D:\jdk102\lib\classes.zip;D:\src\tries
             > D:\jdk11\bin\java HelloWorld
               # FAILS: exception in thread NULL - wrong system classes


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

     Here's some Solaris examples, assuming the application class is

     /usr/src/com/devjoes/killer/App.class

     and it is in package com.devjoes.killer:

             # JDK 1.1, no CLASSPATH set
             $ /usr/bin/jdk11/bin/jre  -cp /usr/src   com.devjoes.killer.App
               # OK:

             $ cd /usr/src/com/devjoes/killer/
             $ /usr/bin/jdk11/bin/java App
               # fails: class name and path are wrong

             $ CLASSPATH=/usr/src/
             $ /usr/bin/jdk11/bin/java App
               # fails: class name is com.devjoes.killer.App

             $ /usr/bin/jdk11/bin/java com.devjoes.killer.App
               # OK:


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

     Here's some javac examples, for both Solaris and Windows, based on the
     following:
      Source files                package           Makes the call
      /usr/src/pack/Minimal.java  package pack      pack.sub.Try.run()
      /usr/src/pack/sub/Try.java  package pack.sub  (nothing)

             $ CLASSPATH=""
             $ /usr/bin/jdk11/bin/javac /usr/src/pack/sub/Try.java
               # OK: works fine

             $ /usr/bin/jdk11/bin/javac /usr/src/pack/Minimal.java
               # FAILS: can't find pack.sub.Try

             $ cd /usr/src
             $ /usr/bin/jdk10/bin/javac pack/Minimal.java
               # OK: finds pack.sub.Try based on . as package root

             $ cd /usr/src/pack
             $ CLASSPATH=/usr/src
             $ /usr/bin/jdk11/bin/javac Minimal.java
               # OK: finds pack.sub.Try based on CLASSPATH


     Now assume the killer application class

     /usr/src/com/devjoes/killer/FastApp.java

     (in package com.devjoes.killer) uses a third-party package in a jar
     file

     /usr/jars/JShapes.jar

     but makes no other reference to other classes. The following works
     fine:

             $ CLASSPATH=/usr/jars/JShapes.jar
             $ cd /usr/src/com/devjoes
             $ /usr/bin/jdk11/bin/javac killer/FastApp.java


     Finally, some applet examples. Many applets only use one class, in the
     same directory as the html file:

     


     To use classes in subdirectory, use the codebase parameter:

     Advanced gets you a dialog. Here, make sure the
     "Prevent MS-DOS-based programs from detecting Windows" checkbox is
     UNCHECKED.

     If the option is checked you get exactly the kind of behavior you're
     seeing. The option is unchecked by default, so it must have been
     selected at some time in the past. Change it back to unchecked.

 19. (Sect. 4) I'm using Notepad to edit my files, and how can I save them
     with the extension ".java"? Also, in notepad some source files have all
     the characters on one line. Why is that?

     [*] First answer: put the entire filename in quotes in the save dialog.
     Once you have created your first Java file, double click on it in
     Explorer, select "Notepad" from the "Open with" box, and Notepad will
     stop adding the spurious ".txt" to your .java files.

     Second answer: Notepad expects to see a "carriage return/line feed"
     pair at the end of each line, rather than just the "newline"
     (line-feed) commonly used on Unix. Use this program to expand all
     newlines,

     /*
      * Usage: jre crlf file1.java file2.java ... fileN.java
       */

     import java.io.*;
     class crlf {
         public static void main(String s[]){
             byte b[]; byte p;
             FileInputStream is;
             BufferedOutputStream os;
             File f;
             for (int i=0; i < s.length;i++){
                 try{
                     f=new File(s[i]);
                     b=new byte[(int)f.length()];
                     is = new FileInputStream(f);
                     is.read(b); is.close();
                     os = new BufferedOutputStream(
                     new FileOutputStream(s[i]),b.length);
                     p='?';
                     for(int j=0; j < b.length; j++){
                         if((p!='\r')&&(b[j]=='\n')) os.write('\r');
                         p=b[j]; os.write(p);
                     }
                     os.flush(); os.close();
                 }catch(IOException e){
                     System.err.println(e.toString());
                 }
             }
         }
     }


     The source code is to show new users a way to make a simple program
     which can read a file and write it out buffered.

     Compile with "javac crlf.java" and run with
     java crlf outfile.txt
     or just use Wordpad instead of Notepad. Wordpad is under
     Start->Programs->Accessories->WordPad

 20. (Sect. 4) How do I fix the message about "out of environment variable
     space"?

     [*] This occurs under Windows when you have long CLASSPATH names. You
     need to increase the environment space. On Windows 95,8 put this in
     your c:\windows\system.ini

             [NonWindowsApp]
             CommandEnvSize=4096


     On NT you can right-click on My Computer, select System Properties then
     go to the Environment tab and then increase COMSPEC to the value you
     want.

     The previous suggestion to put this in your config.sys:

             shell=command /e:4096


     apparently causes you to create two copies of command.com which wastes
     memory.

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

5. Compiler Messages

     Most of the "questions" in this section are diagnostic messages from
     the compiler. Each answer explains what the message means, and how to
     avoid it.

  1. (Sect. 5) Why did I get an OutOfMemory error when porting working code
     from JDK 1.0.2 to 1.1?

     [*] The preset memory limit has changed. It went down to 16MB so as not
     to penalize low memory machines. You can adjust it with

          java -mx128m Frotz        # jdk 1.1
          java -Xmx128m Frotz       # jdk 1.2


     to get a 128MB extent.

     Also see the Runtime methods freeMemory() and totalMemory().

  2. (Sect. 5) Why do I get a "Statement not reached" error from javac for
     no apparent reason?

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

  3. (Sect. 5) class MyOrdinaryClass must be declared abstract.
     It does not define void actionPerformed(java.awt.event.ActionEvent)

     [*] This is one of those error messages where the compiler tries to
     guess what you meant, and gives you a message based on a wrong guess!
     So the message is confusing.

     Your MyOrdinaryClass class implements ActionListener, which means you
     must include a definition of the methods from the ActionListener
     interface.

     But you did not. You either left a method out, or (more likely) you
     misspelled its name. Perhaps you wrote "ActionListener" instead of
     "actionListener".

     So the compiler did not find the method to fulfill the interface. Since
     there was a method promised but not supplied, the compiler thinks you
     were aiming at an abstract class, and it prints an error message
     accordingly.

  4. (Sect. 5) Variable may not have been initialized.

         URL test;
         try {
          test = new URL("http://osprey.avs.dec.com");
         } catch (MalformedURLException e) {
          System.out.println("bad URL:" + e.getMessage());
         }
         System.out.println("this is url " + test);


     [*] The compiler will warn you if you use a variable before it is
     certain to have been initialized (not just with the default value)
     since this means you probably forgot to set it.

     In the case of exceptions, you have to consider that the flow of
     control may terminate abruptly, with no operations completed. In the
     example above, if an exception is raised in the try clause, variable
     test will not be assigned a value, yet you are using it after the catch
     clause. One solution would be to declare test with an explicit initial
     value of null, but this works only because toString() works on a null
     reference. (toString() is invoked implicitly by operator + with String
     operand.)

     Always initialize to a value that will work notwithstanding exceptions
     being thrown.

  5. (Sect. 5) No constructor {superclass}()
     I extended the class called Frotz, and the compiler is giving me an
     error message "No constructor Frotz()" in the child class. Why?

     [*] When you define a constructor for a class, the compiler inserts a
     call to the superclass' parameterless constructor unless you explicitly
     call the superclass' constructor at the start of your constructor. If
     the superclass doesn't *have* a parameterless constructor, the compiler
     emits a message to that effect. The solution is usually to call the
     superclass' constructor at the start of your constructor.

  6. (Sect. 5) No constructor matching MyCheckbox(myApplet)

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

         bp1 = new MyCheckbox(this);
         ^

     [*] If a compiler isn't finding a constructor you thought you created,
     check whether you gave a return value to the method (remember,
     constructors have no return value). E.g.,

         public void MyCheckbox( Container parent )


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

  7. (Sect. 5) Type expected {public method variable}

         public static void main(String[] args) {
         ^
         Statement expected.
         public static final float Conversion_Factor = 39.37;
         ^
         Type expected.

     [*] Argument and variable declarations inside methods are never public
     or static because they are local to a method. (Before JDK 1.1 they
     couldn't be final either, but there was no good reason for that
     restriction and it was dropped.) If you have public or static
     variables, move them outside the method. They are usually put at the
     beginning of the class.

  8. (Sect. 5) Can't access protected method clone in class java.lang.Object

         T.java:96: Can't access protected method clone in
         class java.lang.Object. OtherT is not a subclass of
         the current class.

     [*] Object.clone() is protected because subclasses might want to
     restrict access to cloning, and if Object.clone() were declared public,
     subclasses could never make it more restrictive. The subclass can make
     access to the clone() operation less restrictive.
     This means that a method can clone its own objects, but a method cannot
     clone objects of another class, unless you do something like:

         class SomeObject implements Cloneable {
             public Object clone()
                 throws CloneNotSupportedException {
                 return super.clone();
             }
         }


     i.e., override clone() to make it public, and call the superclass
     clone().

         class Foo {
          Bar bar;
          Foo (Bar b) {
              try {bar = (Bar) b.clone();}
              catch (Exception e) {}
          }
         ...
         class Bar implements Cloneable {
          public Object clone()
              throws java.lang.CloneNotSupportedException {
              return super.clone();
          }
         }


     Another refinement is to note that Object.clone() only throws a
     CloneNotSupportedException when the object doesn't implement Cloneable.
     Since you control what your classes do and don't implement, you can
     ensure that Cloneable classes implement the interface, and you don't
     need to make the overridden clone() throw the exception.

         public class X implements Cloneable {
             public Object clone() { // no throws
                 try {
                           // in case members need cloning
                     X c = (X)super.clone();
                     return c;
                    } catch (CloneNotSupportedException e) {
                    // should not happen, because of Cloneable
                        throw new InternalError();
                    }
                }
         }


  9. (Sect. 5) Deprecated methods
     What does "deprecated" mean? I got this in a compiler error message.

     [*] "Deprecated" means you are using an older API, that Sun has
     replaced with a newer one (usually to follow more consistent naming
     conventions). Deprecated methods are not recommended for use. They are
     supported in the short term, but your code should be updated with the
     new. To update your code, compile your old code using javac's
     "-deprecation" option to list deprecated methods, then find the
     replacement methods in the current HTML API documentation for the old
     deprecated methods.
     As an example of a deprecated API, Component.size() was replaced by
     Component.getSize().

     See also
     http://java.sun.com/products/jdk/1.1/docs/guide/
     misc/deprecation/index.html, "1.1 Deprecated Methods"
     and
     http://java.sun.com/products/jdk/1.1/docs/guide/
     awt/DeprecatedMethods.html, "Deprecated methods in the 1.1 AWT"

 10. (Sect. 5) double y = sin(90);
     What's wrong? That code provokes compiler messages.

     [*] You need to write it this way:

         double cvtDegToRad = Math.PI/180;
         double x = 90*cvtDegToRad;
         double y = Math.sin(x);


     sin is a static method of the Math class that takes radians. You need
     to use the "Math" classname, e.g. Math.sin instead of plain sin,
     because you have to say what class or object these methods belong to.

     A very common mistake is to assume that importing a class means that
     you don't have to qualify the names of its members. When you call a
     method you have to state the name of the class or object it belongs to,
     regardless of any imports you have done. (Except inside the class
     itself, obviously).

     The trig functions are static methods of the Math class, so you give
     the name of the class in invoking them. Further, the Math class works
     in radians, not degrees. 360 degrees = 2 pi radians, so use a
     conversion factor as shown if you are working with degrees.

 11. (Sect. 5) Can't make static reference to method...

     [*] Your code probably looks something like this:

         class myclass {
             public static void main(String args[]) {
               myMethod();
             }
             public void myMethod() { //some code
             }
         }


     Static (class) methods can only call without qualification other static
     methods, so you either have to qualify the call in (static) main() to
     (nonstatic) myMethod() with an object of type myclass, or you have to
     make myMethod() static.

     People often forget that even though main is "in" myclass, there is no
     implicit object when you are in main() because it is static. This
     happens especially when writing code to run an applet as an
     application, where you want to call init() and start() from main.

         public static void main(String[] args) {
             Applet ma = new myApplet(); // have to create object
             ma.init();  // use to qualify access to non-static methods
             ma.start();
         }


 12. (Sect. 5) Incompatible type for =. Explicit cast needed...

         byte b = 0;
         Incompatible type for =.
         Explicit cast needed to convert int to byte.
         b = b + 100;    // compiler error message
         b += 100;       // works OK


     [*] Arithmetic expressions are promoted to the type of the longest,
     floatiest operand in them, or at least to int. The first statement
     involves the assignment of an expression. The expression is promoted to
     32 bits, and must be cast back down to 8 bits, like this: b = (byte)
     (b+100); The second is an operator assignment, and the cast back to
     byte takes place automatically. The Java Language Specification says
     that a compound assignment expression of the form E1 op= E2 is
     equivalent to E1 = (typecast)((E1) op (E2)), where "typecast" is the
     type of E1, except that E1 is evaluated only once. (See JLS 15.25.2
     Compound Assignment Operators) The compile-time narrowing of constants
     means that code such as:

         byte theAnswer = 42;


     is allowed, with no cast necessary. (See JLS 5.2 Assignment Conversion)

     Other sites:
     JLS 5.2 Assignment Conversion
     JLS 15.25.2 Compound Assignment Operators

 13. (Sect. 5) Class {package}.{class} not found in type declaration.
     I am trying to compile file "{class2}.java" in a package, and I get
     this compiler error. {class2}.java refers to {package}.{class}, but the
     file {class}.java and {class2}.java are in the same {package}
     directory, which is the current directory and which is in the CLASSPATH
     variable. Both files have "package {package};" at the top of the file.
     What's the problem?

     [*] When the source refers to classes in packages, the CLASSPATH has to
     point to the root of the package/directory hierarchy for a reference to
     resolve correctly. This is true even for source files in the same
     package (and directory). I.e., assuming {class} and {class2} are both
     in {package}, {class} can't make a reference to {class2} unless the
     CLASSPATH is set so javac can find {package}/{class2}.java. It should
     make no difference what directory you are in when you invoke javac,
     unless you are relying on "." in the CLASSPATH to point to the package
     root or are specifying the source file with a relative path (e.g.,
     {package}/{class}.java).

     Some examples, assuming
        o - Foo.java and Bar.java are in /java/source/pack/
        o - Both have "package pack;" as the first statement
        o - Foo.java includes "Bar b = new Bar();"

         # solaris ksh
         $ alias jc=/java/jdk11/bin/javac
         $ CLASSPATH=/java/source/
         $ jc /java/source/pack/*.java  # works fine
         $ cd /java/source/pack
         $ CLASSPATH=.
         $ jc *.java         # fails - Foo.java can't find class Bar
         $ cd ..             # now . is package root, /java/source/
         $ js pack/*.java    # works


 14. (Sect. 5) public class "Foo" must be defined in "Foo.java"
     I get this message even though it is in Foo.java. What gives?

     [*] Javac verifies that a public class is defined in a file of the same
     name (e.g., that public class Foo is defined in Foo.java). Two things
     you can check:

     First, make sure the case matches exactly. public class Foo cannot be
     in foo.java; it has to be in Foo.java.

     Second, are you using MKS on win32? Javac on win32 assumes you are
     using the DOS path separator (\) even though MKS accepts the Unix path
     separator (/). When javac tries to parse a your Unix-style path, it
     won't produce the correct filename, the match will fail, and it will
     emit an error. You have to use the DOS path separator (\), which must
     be escaped in MKS - e.g., "javac H:\\source\\package\\Foo.java".
     Alternatively, you can traverse to each source directory and avoid
     pathnames altogether.

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

6. Java Language Issues

     How-to

  1. (Sect 6.) How do I compare two Strings?

     if (s1 == s2)

     is giving me funny results.

     [*] The comparison using "==" on objects, such as Strings, is asking,
     "Do these two objects have the same reference?" Do they have the same
     address, and hence are the same object? What you really want to do is
     ask, "Do these two Strings have the same *contents*?"
     Compare String contents with any of the following:

         if (s1.equals(s2) )
         if (s1.equalsIgnoreCase(s2) )
         if (s1.startsWith(s2) )
         if (s1.endsWith(s2) )
         if (s1.regionMatches(s1_offset, s2, s2_offset, length) )
         if (s1.compareTo(s2) < 0)


     (There are other ways, too.)
     Note that you can do this with literals:

     if ("apple".equals(s2) ) ...


     If you compare these the other way round, like this:

     if ( s2.equals("apple") ) ...


     and s2 is null, you will get a null pointer exception.

  2. (Sect. 6) How do you get the code value of a char?
     I would like to transform a char into the corresponding int value, that
     represents the code value of the char. How?

     [*] Like this.

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


     Going the other way is just

         c = (char) i;


     This question crops up so frequently because the BASIC language uses
     functions to map characters into ints, ASC( 'A' ) => 65 causing BASIC
     programmers to seek the corresponding Java functions. The same is true
     for Pascal, Ada, and other languages.

  3. (Sect. 6) Why does b >>>= 1 give me the same result as b >>= 1?

     [*] ">>" is a "signed" or "arithmetic" shift, namely, it replicates the
     sign bit on the left as it shifts.
     The ">>>" operator is an "unsigned" or "logical" shift; it does a shift
     right and zero fill. However, ">>>" looks like it does a signed shift
     with negative bytes and shorts, where int promotion alters the sign.

     This occurs when you have a non-canonical type, byte, or short, with a
     negative value, e.g.

         byte b = -15; // 0xf1
         b = (byte) b >>> 4; // why isn't b 0x0f ?


     The initial expectation is that an unsigned shift right of 0xf1 would
     successively be (in binary)

         0111_1000 then
         0011_1100 then
         0001_1110 then
         0000_1111


     But that doesn't happen. The rules of arithmetic in Java say that all
     operands are converted at least to int before the operation (and
     possibly to a more capacious type). That means our byte is promoted to
     an int, so instead of shifting 0xf1, we are shifting 0xfffffff1. If you
     shift right unsigned 4 places, you get 0x0fffffff. When you cast that
     to a byte it becomes 0xff, or -1.

     The bottom line is that the final result is the same as if you had
     performed the signed shift because the unsigned shift applied to the
     intermediate int, not to the original byte. This anomaly means that
     ">>>" is useless for negative bytes and shorts. It is probably safer
     and clearer not to use it at all, but to mask and shift instead:

         byte b = -15;
         b = (byte) (b>>>4);
         System.out.println("b= "+Integer.toHexString(b) );
         // recommended
         b = -15;
         b = (byte) ( (b & 0xFF) >> 4 );
         System.out.println("b= "+Integer.toHexString(b) );


  4. (Sect. 6) Why does the  happen in floating point?

     [*] There are several unexpected things that seem to bite programmers
     with floating point. This is almost always a result of the programmer
     not being fully conversant with floating point arithmetic in general,
     rather than a problem relating to Java.

     The question of floating point accuracy comes up with Java more than
     with C++ (for example) because of Java's decision in the println()
     method to print enough digits to distinguish the number from the
     next-closest number, rather than rounding it to 6 significant digits by
     default as the C/C++ libraries do. [ISO C, Sect 7.9.6.1, line 21 of
     "the double argument"]

     If you seem to be having problems with floating point, the problem
     probably stems from the fact that floating-point arithmetic is
     inherently imprecise. You can expect up to 7 digits of precision with
     floats and 16 digits with doubles. However, that does not mean that a
     number that can be exactly represented in 7 digits decimal or can be
     exactly represented as a binary floating point number. On the contrary,
     that is usually not the case.

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

     There is a limitation of FP in JDK 1.0 (fixed in JDK 1.1). Namely, when
     you output a floating point number in Java 1.0, the result is
     system-dependent and contains no more than six digits after the decimal
     point. This bug is fixed in Java 1.1.

     For more information and detailed specifications on how Java deals with
     floating point, see the URLs listed below.

     Other sites:
     What Every Computer Scientist Should Know About Floating Point.
     http://java.sun.com/products/jdk/1.1/compatibility.html#incompatibilities

     JLS 4.2.3 Floating-Point Types and Values
     JLS 4.2.4 Floating-Point Operations
     JLS 3.10.2 Floating-Point Literals
     JLS 5.2.3 Narrowing Primitive Conversions

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

     Understanding the Java Language

  5. (Sect. 6) How can I program linked lists if Java doesn't have pointers?

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

     Java does not have pointer arithmetic or untyped casting. By removing
     the ability for programmers to create and modify pointers in arbitrary
     ways, Java makes memory management more reliable, while still allowing
     dynamic data structures. Also note that Java has NullPointerException,
     not NullReferenceException.

     A linked list class in Java might start like this:

         public class LinkedList {
             public LinkedList head;
             public LinkedList next;
             public Object data;
             public LinkedList advanceToNext(LinkedList current) { ...
         }


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

  6. (Sect. 6) Are parameters in Java passed by value or by reference?

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

     Bottom line: The caller's copy of primitive type arguments (int, char,
     etc.) _do not_ change when the corresponding parameter is changed.
     However, the fields of the caller's object _do_ change when the called
     method changes the corresponding fields of the object (reference)
     passed as a parameter.

     Also in this FAQ:
     How can I program linked lists if Java doesn't have pointers?
     Other sites:
     JLS 8.4.1 Formal Parameters

  7. (Sect. 6) What are "class literals"?

     [*] A feature introduced in JDK 1.1. They are literals of type "Class"
     that hold a value representing any class. There are even values to
     represent "void" and an array, like this:

         Class myCl1 = Character.class;
         Class myCl2 = Void.class;
         Class myCl3 = Object.class;
         Class myCl4 = String[].class;
         Class myCl5 = int[][].class;


     You might use it like this:

         Class cl = thing.getClass();
         if (cl.equals(myCl1))
         System.out.println("It's a Character class");


     Note that a class literal

             Component.class


     is the equivalent of

             Class.forName("java.awt.Component")


     The second can throw an exception, but the first cannot. If you don't
     know the name of the class when you write the code, you cannot use the
     first form.

  8. (Sect. 6) What are the naming conventions in Java?

     [*] The naming conventions are straightforward:
       1. Package names are guaranteed uniqueness by using the Internet
          domain name in reverse order: com.javasoft.jag - the "com" or
          "edu" (etc.) part used to be in upper case, but now lower case is
          the recommendation.
       2. Class and interface names are descriptive nouns, with the first
          letter of each word capitalized: PolarCoords. Interfaces are often
          (not always) called "something-able", e.g. "Runnable", "Sortable".
          Caution: java.util.Observable is not an interface, though
          java.util.Observer is. These two are poorly designed.
       3. Object and data (field) names are nouns/noun phrases, with the
          first letter lowercase, and the first letter of subsequent words
          capitalized: currentLimit
       4. Method names are verbs/verb phrases, with the first letter
          lowercase, and the first letter of subsequent words capitalized:
          calculateCurrentLimit
       5. Constant (final) names are in caps: UPPER_LIMIT
       6. Also in the FAQ:
          Where can I find a Java style guide on naming conventions?
          Other sites:
          JLS 6.8 Naming Conventions

  9. (Sect. 6) Should I prefer importing {package}.{class} over {package}.*?

     Does it make a difference to the class file in any way, if I import a
     package versus use the full name, i.e.

         import java.rmi.server.*;
         ...
         RemoteObject ro;

     versus:

         java.rmi.server.RemoteObject ro;

     [*] No, it makes no difference to the class files or runtime speed.
     Import is just a shorthand for quoting the full name package and class
     name (as in the examples in the question). Importing a class does not
     cause the class to be loaded at run time. There is no runtime penalty
     for using the * form of import. The class file will contain the name of
     the packages it uses, and the loader will look for those classes as
     needed at runtime.

     At compile time, the different forms of import may or may not make a
     difference to compile time. Such a difference is likely to be
     negligible, and should not be a factor in which form of import you use.

     However, there are style advantages. Some say that stating which
     classes you are importing can help program readability. In a program
     with many * import statements, it may take a programmer time to find
     which package an obscure class is imported from. If you explicitly list
     each class you import at the top of the program, you document which
     package each class you use comes from. These people suggest that you
     use

     import java.rmi.server.RemoteObject;


     in preference to:

     import java.rmi.server.*;


     Other people say that it is clearer still to use the full package and
     class name, at the point where you use classes in other packages.
     These people suggest that you use:

     java.rmi.server.RemoteObject ro;


     But that gets a little lengthy when you instantiate:

             java.rmi.server.RemoteObject ro
                       = new java.rmi.server.RemoteObject();


     You always have the option of stating the full package and class name,
     whether you use import or not.

     Another good reason not to use the * form is when you are importing two
     packages that have classes of the same name and you want to use only
     one of those classes. E.g.

         import com.sun.*;
         import com.ms.*;


     where there is a class called Modem in both those packages. If you use
     the * form of import, you import both of the Modem classes and then
     must fully qualify the class each time you use it, to say which of the
     two you mean.

     In Java 1.0, if you import a class that has the same name as a class
     defined in that source file, you will get an error that the class names
     clash. In Java 1.1, the local class will be used when the package name
     is not given; to use the imported class, you have to use the full
     package name.

     The best advice is to write the program so that it is as readable as
     possible. Where you have a group of well-known classes, as in java.awt,
     there is no reason not to use "import java.awt.*;"

 10. (Sect. 6) How can I use Math.cos() etc. without the prefix "Math."?
     Is there some declaration that I can use to make "acos", "cos", "sin",
     etc. (from java.lang.Math) recognizable in my own class, so I don't
     have to prefix "Math." to them?

     [*] No. There is no good alternative. There are several bad
     alternatives:
       1. Using "import" doesn't work.
          The import stament only imports packages, subpackages, and
          classes, not class members. This doesn't work:

                  import java.lang.Math.*;


       2. Minimizing class name usage is unclear and bad style.
          - You could wrap the functions in your own class.

              double sin(double x) {
                  return Math.sin(x);
              } // etc. for each function


          But you'd have to use your class name everywhere but inside your
          class, so it doesn't help.
          - You can make a null reference to the Math class and use it to
          refer to the static methods. Declare

              java.lang.Math M = null;
              angle = M.cos(i);


          Besides not being clear, this invites abuse and errors.

          - You could inherit the names
          If java.lang.Math were not final and your class did not extend
          another class, you could have your class extend Math, to bring the
          namespace in. However, it is poor OOP style to use inheritance to
          obtain a name abbreviation rather than to express a type
          hierarchy.

 11. (Sect. 6) Why is there a standard JNI?

     [*] JNI is the Java Native Interface. It defines the way that a Java
     program can call C programs. The industry has agreed on, and Sun has
     codified, JNI as the standard. Microsoft shuns the standard and uses a
     protocol of its own called Raw Native Interface, RNI.

     You might think that once a Java program uses JNI, portability is lost,
     and hence it doesn't matter if vendors diverge from the JNI standard.
     Not so. Code that accesses a native library using JNI can run on any VM
     that supports JNI, so it's portable across VMs on the same platform.
     Further, you can port a native library to all platforms Java supports
     (indeed, this is how Sun implements the Java Platform), so JNI
     _enables_ cross-platform development where it's necessary to use
     platform-specific idioms for certain functionality.

     Conversely, code that uses RNI can only run on Microsoft's VMs on the
     win32 platform. Microsoft's RNI has the effect of limiting RNI programs
     to the Microsoft VM. Further, Microsoft's failure to support JNI locks
     out JNI-based functionality on Windows. Microsoft's non-standard RNI is
     the reason that programs using the Microsoft JVM cannot use the
     standard Java jdbc-odbc library. That library has a piece written in C.
     It works for all JVMs except Microsoft's.

     The standard JNI thus has two purposes:
       1. Source code compatibility between different platforms.
       2. Binary code compatibility between different JVMs on the same
          platform.
     Microsoft's use of RNI locks in programmers who use it, and Microsoft's
     failure to support JNI locks out programmers who don't use RNI. Users
     can't run standard JNI applications on Microsoft VMs, or RNI
     applications on non-Microsoft VM's. As a result, since most users will
     support only one VM, they'll be locked in to complementary software -
     in the case of Microsoft, a proprietary standard. A standard JNI means
     that you can use any standard JVM to run your code on this platform.

 12. (Sect. 6) How do I find out more about JNI? How do I find out more
     about Java Anything?

     [*] Taking the questions one at a time. Use of JNI detracts from
     program portability. So you would only do it when you need some
     critical single-platform effect. The documentation on JNI is at:
     http://java.sun.com/docs/books/tutorial/native1.1/index.html

     If your interest extends to reading a book on JNI, a good one is
     "Essential JNI Java Native Interface" by Rob Gordon; ISBN
     0-13-679895-0. Available from Amazon.com and book outlets everywhere.

     In general, if you want to find out about topic "X" in Java, your first
     stop should be to search the http://java.sun.com website for "X". For
     example if you want to know about Internationalization in Java, a
     search at the site quickly takes you to
     http://java.sun.com/products/jdk/1.1/docs/guide/intl/intlTOC.doc.html.

 13. (Sect. 6) How do I get unsigned ints in Java?

     [*] Java doesn't have unsigned ints. The reason is that this is a
     poorly designed area of C. The rules for what type you end up with when
     you mix signed and unsigned in expressions are complicated, and they
     changed between K&R and ANSI C (you might have heard this under the
     name "unsigned preserving vs. value preserving"). Worse, they depended
     on the underlying hardware, so they varied from platform to platform,
     causing bugs in all kinds of unexpected places. The book "Expert C
     Programming" goes into this in more depth (page 25). So, to avoid
     bringing over the hidden complexities, Java does not bring over
     unsigned types from C.
     Use type char if you are OK with 16-bit unsigned quantities. Otherwise,
     go to the next larger type and use masking. Specifically, to convert an
     int to its unsigned representation, use:

             ((long)i) & 0x00000000FFFFFFFFL


     This promotes the signed int to long (with sign extension) then chops
     off the sign-extension, leaving it as a positive 32-bit quantity held
     in a 64-bit type.
     Also worth noting is that if you're going to work with unsigned bytes,
     int is a more efficient larger type to use than short or char, since
     smaller values have to be promoted to int to do any arithmetic or
     testing on them.

 14. (Sect. 6) What happened to "private protected"?

     [*] It first appeared in JDK 1.0 FCS (it had not been in the betas).
     Then it was removed in JDK 1.0.1. It was an ugly hack syntax-wise, and
     it didn't fit consistently with the other access modifiers. It never
     worked properly: in the versions of the JDK before it was removed,
     calls to private protected methods were not dynamically bound, as they
     should have been. It added very little capability to the language. It's
     always a bad idea to reuse existing keywords with a different meaning.
     Using two of them together only compounds the sin.

     The official story is that it was a bug. That's not the full story.
     Private protected was put in because it was championed by a strong
     advocate. It was pulled out when he was overruled by popular
     acclamation.

     Inheritance

 15. What are the differences between an interface and an abstract class?

     [*] Some use a semantic distinction: an abstract superclass models the
     "is" relationship, while an interface models the "has" relationship.
     The rule would thus be, if it's a subtype, inherit; otherwise,
     implement. But where the object boundaries are themselves at stake,
     it's circular to state this unless there are real-world metaphors to
     distinguish the objects from their properties and parents. So where
     there are no real-world metaphors, you have to understand the practical
     differences in Java (esp. vs. C++).

     Most differences between interfaces and abstract classes stem from
     three characteristics:
       1. Both define method signatures that a derived class will have.
       2. An abstract class can also define a partial implementation.
       3. A class can implement many interfaces, but inherit from only one
          class.

     In greater detail, these topics are:
       1. Method signatures Both interfaces and abstract classes permit one
          to treat the derived-type class as the derived-from-type class.
          Both define a set of available methods in a way that can be
          enforced by the type-checking mechanism. This is typically used to
          permit different (derived) types to behave in the same way (as
          what they are derived from - i.e., they all support particular
          methods). For example, all java.* types can be printed as Strings
          because Object, the superclass of all java.* types, has a
          toString() method. Similarly, all types that implement the
          Observable interface can be passed an Observer to signal when an
          event has occurred. This permits an algorithm or service to
          operate on different (derived) types as if they were the same
          (derived-from) type.
          This mechanism supports not only polymorphism (one object treated
          as another), but differentiation. In either case, the (derived)
          types can implement the method in the way appropriate to that
          type. However, you're not likely to override inherited
          functionality, but you must implement interface methods, so if you
          expect significant differentiation, then an interface might be
          warranted.
          Finally, this mechanism supports a weak variant of access control.
          Only inherited methods are available to callers who only have a
          reference to the superclass or interface type. It's weak because
          they can attempt a narrowing cast if they know their target type.
          Nonetheless, it reduces some complexity.
       2. Inheriting implementation Inheriting an implementation is useful
          where the code should be shared. This happens where derived types
          vary the functionality only a little bit, or where a complex set
          of method interfaces can through mutual reference be implemented
          with relatively few methods that can be implemented by derived
          types. You can also reuse code by having your class use or keep an
          object of another type that implements that code, but that doesn't
          permit your callers to treat you in a particular way. To both
          "get" functionality and to be treated "as" the superclass are the
          essentials of the type/subtype relationship.
       3. Java's rule of single inheritance Java differs from C++ in
          permitting only single inheritance. This makes for some difficult
          choices, if you would like to share combinations of inherited
          functionality and polymorphism from more than one source. However,
          it does reinforce the notion of inheritance as a subtyping (is)
          relationship, and implicitly that type relationships form a tree
          rather than a network.

     Other differences to consider:
       1. Abstract class implementations may include fields
       2. Interfaces may include final data members
       3. It is slightly slower to call an implemented method via an
          interface reference. There is an even smaller penalty for calling
          a superclass method via a subclass reference (i.e., where the
          subclass does not override the method). There is almost no penalty
          for calling a subclass method via a superclass reference. (All are
          compared to a direct method call, i.e., calling the derived class
          method via a derived class reference).

 16. (Sect. 6) How do static methods interact with inheritance?

     [*] Static (per-class, rather than per-object) methods do not
     participate in overriding (choosing the right method at runtime based
     on the class of the object). Probably the best and simplest way to
     think about this (and to write your code) is to write every invocation
     of a static method using the fully qualified class name:

         class A {
         public static method1() {
                 A.method2();
             }
         public static method2() {
             }
         }

         class B extends A {
             public static method3() {
                 A.method1();
             }
             public static method2() {
             }
         }


     Now it is perfectly clear that the static method2() that is called is
     A.method2(), not B.method2(). A.method2() will be called regardless of
     whether you use the fully-qualified class name or not, but using "A."
     makes it obvious to all.

 17. (Sect. 6) Why is the String class final? I often want to override it.

     [*] Being final guarantees that instances of String are read-only. (The
     String class implements read-only objects, but if it were not final it
     would be possible to write a subclass of String which permitted
     instances to be changed.) Strings need to be read-only for security and
     efficiency.

     As for efficiency, Strings are very commonly used, even behind the
     scenes by the Java compiler. Efficiency gains in the String class yield
     big dividends. If no one can change a String, then you never have to
     worry about who else has a reference to your String. It's easier to
     optimize accesses to an object that is known to be unchanging.

     Security is a more compelling reason. Before String was changed to be
     final (while Java 1.0 was still in beta) there was a race condition
     which could be used to subvert security restrictions. It had to do with
     one thread changing a pathname to a file after another thread had
     checked that the access was permitted and was about to open it.

     There are other ways to solve these problems, but the designers
     preferred making String final, particularly since the StringBuffer
     class is available as an alternative.

 18. (Sect. 6) If I extend/subclass a class, are the constructors inherited?

     [*] "Constructor declarations are not members. They are never inherited
     and therefore are not subject to hiding or overriding." The default
     constructor is not inherited, but provided. (See JLS 8.6.7 Default
     Constructors)

     If you don't give your child class any constructors, a default no-arg
     constructor that invokes the superclass' constructor is provided for
     you. If the superclass doesn't have a no-arg constructor, you should
     create a constructor and call the appropriate superclass constructor.

     Also in the FAQ:
     Compiler message No constructor {superclass}()

     Other sites:
     JLS 8.6.7 Default Constructors

 19. (Sect. 6) How can I safely store particular types in general
     containers?
     I often want to store particular types of objects but don't want to
     subclass my basic storage classes to enforce the particular type; that
     would make for too many subclasses (e.g., IntegerLinkedList,
     StringLinkedList, etc.).

     [*] Generic programming in java (the rough equivalent of C++'s
     templates) works reasonably well since all java classes are subclasses
     of Object. There is, however one potential problem - there is always a
     possibility that a generic container may contain different classes of
     objects.

     This naturally leads to the question of how to do this in a type-safe
     way. If you've created a generic LinkedList class, how can you be type
     safe without having to create a multitude of subclasses
     (IntegerLinkedList, StringLinkedList, etc.)?

     One way to handle this would be to offer up an additional constructor
     in your generic class that takes a parameter of type "Class" and uses
     that parameter along with Class's "isInstance" method to guarantee that
     Objects added to the container are the expected type.

         public class LinkedList {
             Protected Class type = Object.class;

             public LinkedList(Class type) { this.type = type; }

             public void addElement(Object element) throws Exception
             {
             if(!type.isInstance( element ))
                 throw new Exception(
                      "Expected element of type (" + type    + ")" +
                      " got element of type ("     + element + ")"   );
              ...
              }
          }


     Note that the comments in the source for isInstance() refer to a
     "specified Class parameter", suggesting that you are supposed to write
     something like:

             public void addElement(Object element) throws Exception
         {
             Class c = element.getClass();
             if(!type.isInstance(c))


     This works, but the documentation for isInstance is clear that the
     parameter should be an Object rather than a Class. Also, note that
     "Collections" are coming in JDK 1.2, and they provide a much safer and
     more extensible mechanism. More information about this is available at
     the Java Developer Connection at the Java website: http://java.sun.com/

     Method interfaces

 20. How do I send a variable number of arguments to a method?

     [*]
       1. (Easy) Use method overloading to support different parameters.
          This makes things easy on the caller but can get out of hand if
          you want to support a wide number and variety of parameter types.
          You should ask yourself if your code design is well-organized if
          you need to do this.
       2. (More complicated) Use arrays. It's even possible to declare
          arrays inline as shown below:

              foo("A param",
                  new Object[] {"param3", "param4", new Integer(5)} );
           // ...

           void foo(String param1, Object param2[]) {
               System.out.println(param1);
               for (int i = 0; i < param2.length; i++) {
                   System.out.println(param2[i].toString());
               }
           }


          You can even pass arrays of arrays using this method. Of course,
          inside the method you need to be able to decode what the arguments
          are and how you use them.
       3. Alternatively you can invent a class that just contains all the
          possible fields you might want to pass into a method (plus
          booleans to say if each field is set or not), and make an object
          of that class be a parameter to the method. You can return
          multiple values from a method the same ways; either have the
          method return an array or a wrapper object.

     However, remember the wise words of Professor Alan Perlis, "if your
     procedure has more than about half a dozen parameters, you probably
     forgot a few." Passing large numbers of arguments into a function
     suggests your function is badly organized.

 21. (Sect. 6) How can I return a different object in a method parameter?
     How can I pass an object to a method, and have the method change the
     reference so it points to a different object back in the calling code?

     [*] There are two ways. The obvious way is "just add another level of
     indirection". Wrap the object in another class, whose purpose is simply
     to be passed as a parameter, allowing the nested object reference to be
     modified.
     The second alternative is a clearer variant of this. Pass in a single
     element array. Since arrays are objects, this works.

             void jfoo(Object ref[]){
             ref[0] = new Object();
         }
         ...
         Object kludge[] = new Object[1];
         kludge[0]= myObj;
         jfoo(kludge);
         if (kludge[0] == myObj) ...
         else ...


     Note that changing a global variable/object inside a method is an
     egregious programming practice; it usually violates basic OOP
     constructs.

 22. (Sect. 6) How do I get multiple return values back from a method?

     [*] You can just have the function return a Vector. This is
     particularly convenient when you're not sure how much you are going to
     be returning, based on what occurs in the method. A Vector is
     essentially a dynamically-growable array. Regular arrays can't grow
     after you declare them - you have to declare a bigger array and move
     the old stuff into it.

     Arrays

 23. (Sect. 6) How do I allocate a multidimensional array?

     [*] There are several ways. If you want a rectangular array, you can
     allocate the space for the array all at once. The following creates a
     4x5 array:

         int arr[][] = new int[4][5];


     If you want each row to have a different number of columns, you can use
     the fact that a two-dimensional array is actually an array of arrays.
     The following code allocates a triangular array:

         int arr[][] = new int[4][];    // allocate the four row arrays
         for (int i = 0; i < 4; i++) // initialize each of the four rows
         arr[i] = new int[i + 1];       // row i has i + 1 columns


     Note that if you allocate an array of any kind of object (as opposed to
     primitive type), all the references will be null by default. These null
     references can result in NullPointerExceptions if you try to
     dereference them.
     In other words, after doing:

         int arr[] = new int[4];


     you can say

             if (arr[2] == 0)


     But after doing

             Integer Iarr[] = new Integer[4];


     you must fill in the object reference before using it. E.g.,

             Iarr[2] = myInt;


     or

             arr[2] = new Int(27);


     before you can say

             if (Iarr[2].equals(myInt))


 24. (Sect. 6) How do I copy an array?

     [*] If the array only contains primitive types or if you want to copy
     only the object references, not duplicate the objects, then use the
     method

         java.lang.System.arraycopy(Object src, int src_position,
             Object dst, int dst_position, int length);


     Otherwise, if you want to duplicate the objects, you have to initialize
     your new array and write a loop that duplicates each object in the old
     array into the new.

     Note that the documentation for arraycopy() says that if src and dst
     refer to the same object, then arraycopy behaves as if the source array
     elements are copied into a temporary array (i.e., they are preserved).
     Some interpret this as meaning a temporary array will be so allocated,
     but that's not Sun's implementation.

     Other sites:
     JLS 20.18.16 {java.lang.System.arraycopy()}

 25. (Sect. 6) How do I clear an array?

     [*] There is no method to clear an array to 0.0, 0, null, false,
     '\u0000' etc. When you allocate an array, the elements are set to their
     default values, but that doesn't help when you want to reuse an array.

     If you want to set the same array to the same set of values many times,
     create a template array. Fill it with the reset value, then use
     System.arraycopy() to copy it into the work array each time you need to
     set the work array.

 26. (Sect. 6) What is a fast way to set all elements of an array?
     I don't want to use a template array. I would like to set all array
     elements to a given value without duplicating the (possibly large)
     array.

     [*] Using a loop that does it one by one is probably 20 to 40 times
     slower than good old memset() in C.

     A fast way on many VM's is to set the first byte of the array, then use
     System.arraycopy() repeatedly to fill the next byte, the next two
     bytes, the next four bytes, the next eight bytes, etc., and when you
     get past halfway, fill in the rest.

         public static void bytefill(byte[] array, byte value) {
         int len = array.length;
         if (len > 0)
         array[0] = value;
         for (int i = 1; i < len; i += i)
             System.arraycopy( array, 0, array, i,
                 ((len - i) < i) ? (len - i) : i);
         }


     This is faster on Sun's VM than a simple loop, and probably even faster
     under JITs because it only performs at most log2(array.length) bounds
     checks. This is a clever code idiom applying the binary chop algorithm
     to arrays even when their size is not a power of 2.

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

7. I/O

  1. (Sect. 7) How do I read a String/int/boolean/etc from the keyboard?

     [*] The easiest way is to pick up the source for the 100% pure Java
     class EasyIn from http://www.afu.com/ (same place as this FAQ). Compile
     it with your code and use it like this:

     EasyIn easy = new EasyIn();

     int i = easy.readInt(); // gets an int from System.in
     boolean b = easy.readBoolean(); // gets a boolean from System.in
     double d = easy.readDouble(); // gets a double from System.in


     ... etc.

     EasyIn is free, comes with source, and you can do what you like with
     it, including improve it, and send me back the results.

     If, instead, you want to "roll your own" code (why?!), in JDK 1.0.2

     java.io.DataInputStream in = new java.io.DataInputStream(System.in);
     String s = in.readLine();


     One way in JDK 1.1:

     java.io.BufferedReader in =
      new java.io.BufferedReader( new InputStreamReader(System.in));

     String s = in.readLine();


     Once you have the token in a String, it is easy to parse it into one of
     the other types, as shown earlier in the FAQ. Yes, it is bone-headed,
     as it makes the simplest case of keyboard I/O unnecessarily
     complicated. A bug was filed with Javasoft to record this problem, but
     don't count on this being fixed any time soon.

  2. (Sect. 7) Why do I have trouble with System.out.println()? Check the
     spelling. The last two characters are the letters "ell enn" not "one
     enn".

     The name of the method stands for "print line", since it prints a
     String and goes to the next line, rather than staying on the same line
     as System.out.print() does. Yes, the name is yet another Java naming
     inconsistency, since the input equivalent is readLine(), not readln().

  3. (Sect. 7) How do I write to the serial port on my PC using Java?

     [*] There is a platform-independent serial port API introduced in JDK
     1.2. You can download the documentation by registering with the Java
     Developer Connection (it's free, http://java.sun.com) and browsing
     http://java.sun.com/jdc/earlyAccess/communications.html.

     For systems prior to JDK 1.2, read on. At least two companies have
     written a library to drive the port. See
        o http://www.sc-systems.com has a library for Windows 95, WindowsNT,
          OS/2, Macintosh PPC, Solaris Sparc, Linux x86, FreeBSD x86, HP/UX
          PA-RISC, and possibly others too.
        o http://www.cd.com/portio
        o In addition, there is a Unix serial port utility available with
          source at http://jarvi.ezlink.com/rxtx/ It's free under the GPL,
          and works on Linux, Irix, Solaris, Windows 95, and NT.

     While not helpful to typical home users, there is an alternative
     portable COM port solution for Java 1.1 and even 1.0. Buy your COM
     ports in the form of "terminal servers". Using a COM port is now as
     easy as connecting to it with a Socket. Port parameters can be changed
     programatically using SNMP for most terminal servers (but this is never
     necessary when a modern modem or other fixed-rate equipment is
     attached). Any networked box can serve as a terminal server - even
     Win95 - with a simple native server application for that box, but
     buying an actual firmware based hardware box is much easier.

     Furthermore, your Win95 native applications can now share the COM ports
     (and any attached modems) via a Win95 product called "Dial-out IP" at
     http://www.tactical-sw.com/.

     If the port exists as a pathname in the filesystem, you can open it as
     a file and read/write. You can also print text this way by writing to
     "prn" or "lpt1" on a pc, and "/dev/something" on Unix. Writing a
     formfeed at the end of the file is essential on Windows 95. Here is
     some sample code:

     // class that opens the printer as a file
     // and writes "Hello World" to it

     import java.io.*;
     public class lpt {
         public static void main (String[] argv) {
             try {
                 FileOutputStream os = new FileOutputStream("LPT1");
                 //wrap stream in "friendly" PrintStream
                 PrintStream ps = new PrintStream(os);

                 //print text here
                 ps.println("Hello world!");

                 //form feed -- this is important
                 //Without the form feed, the text will simply sit
                 // in print buffer until something else gets printed.
                 ps.print("\f");
                 //flush buffer and close
                 ps.close();
             } catch (Exception e) {
                 System.out.println("Exception occurred: " + e);
             }
         }
     }


     If you wish to change the characteristics of the port (e.g. baud rate,
     parity, etc.), not just read/write data, Java currently offers no
     portable way to do this. You will need to use one of the packages
     mentioned above or some native code or a system command.

  4. (Sect. 7) How do I append to a file?

     [*] There are two ways. JDK 1.1 introduced new constructors for two of
     the output classes that allowed you to set a boolean flag:

     public FileWriter(String fileName, boolean append) throws IOException
     public FileOutputStream(String name, boolean append) throws IOException


     Another way is to do this:

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


     Then write using fd. Note that the latter method does not take
     advantage of the "append" mode present in many operating systems (such
     as all Unixes). Such a difference may make a difference with multiple
     processes or threads appending to the same output file. This can happen
     frequently, even if not intended by the programmer, e.g. with logfiles
     in multitasking environments. With the lack of file-locking mechanisms
     in Java the issue becomes even more significant.

  5. (Sect. 7) Is it possible to lock a file using Java ?

     [*] JDK 1.2 introduces the ability to lock a file (indirectly) using
     the File class. Use createTempFile() with delete on exit. Prior
     releases of Java do not feature an API to lock a file or regions within
     a file. Code that needs to do this must take one of four approaches:
       1. Implement an advisory locking scheme using features that Java does
          have (synchronized methods). This allows you to lock files against
          use by other Java code running in the same JVM.

       2. Use an atomic operation like file "renameTo()" and have all
          processes (Java and non-Java) follow the same protocol: if the
          operation succeeds, you have the lock, and you change the file
          back to give up the lock. The FAQ previously recommended delete()
          or mkdir() as the primitive, but there has been a report that
          these operations are idempotent (can be repeated without error) in
          some JVMs. The suggestion of renameTo has been proven to work in
          practice. See http://www.camb.opengroup.org/~sanfilip/FileLock/
          for example locking class docs and source.

       3. Make calls to native code to issue the locking ioctls. This
          approach is not portable, but gives you a shot at having your
          locks respected by other programs using standard locking ioctls
          outside Java.

       4. Push the work to a central server. Since socket connection
          requests arrive in a single queue on the server, this can be used
          to serialize lock requests. There might be some merit in copying
          the NFS lockd protocol for a general approach. Rolling your own
          simple version for a specific application is pretty easy. A
          database would be better off locking records or fields, not byte
          offsets. In theory, the server socket approach would make it
          easier to perform automatic cleanup of a lock on abrupt VM process
          failure, e.g. by asking "are you still alive?" to the lock holder
          occasionally.

  6. (Sect. 7) How do I make the keyboard beep in Java?

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

     System.out.print("\07");
     System.out.flush();

     should work, and works in JDK 1.0.2, too. That's the ASCII BEL
     character (Java doesn't support the C abstraction of '\a' for an alert
     character).

  7. (Sect. 7) How do I execute