home *** CD-ROM | disk | FTP | other *** search
/ Internet Info 1997 December / Internet_Info_CD-ROM_Walnut_Creek_December_1997.iso / faqs / alt / www / hotjava / comp.lang.java_FAQ < prev   
Internet Message Format  |  1997-10-16  |  134KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!spool.mu.edu!uwm.edu!vixen.cso.uiuc.edu!newsfeed.internetmci.com!128.158.254.10!news.msfc.nasa.gov!bcm.tmc.edu!news.eng.convex.com!newsgate.duke.edu!news-relay.ncren.net!fddinewz.oit.unc.edu!titan.oit.unc.edu!usenet
  2. From: elharo@sunsite.unc.edu
  3. Newsgroups: comp.lang.java.programmer,comp.lang.java.softwaretools,comp.lang.java.gui,comp.lang.java.help,alt.www.hotjava
  4. Subject: comp.lang.java FAQ
  5. Supersedes: <javafaq_876228913@sunsite.unc.edu>
  6. Followup-To: poster
  7. Date: 14 Oct 1997 16:22:23 -0400
  8. Organization: Cafe au Lait
  9. Lines: 3104
  10. Sender: elharo@titan.oit.unc.edu
  11. Expires: 4 Nov 1997 20:22:21 GMT
  12. Message-ID: <javafaq_876860541@sunsite.unc.edu>
  13. NNTP-Posting-Host: titan.oit.unc.edu
  14. Xref: senator-bedfellow.mit.edu comp.lang.java.programmer:90009 comp.lang.java.softwaretools:3204 comp.lang.java.gui:4440 comp.lang.java.help:7843 alt.www.hotjava:6268
  15.  
  16. Archive-name: computer-lang/java-faq/part1
  17. Posting-Frequency: weekly
  18. Last-modified: 1997/10/06
  19. Version: 1.6
  20. URL: http://sunsite.unc.edu/javafaq/javafaq.html
  21.  
  22.                          THE COMP.LANG.JAVA FAQ LIST
  23.                                        
  24.    This is a Java FAQ list for the comp.lang.java newsgroups. If you're
  25.    reading the text version via Usenet, I do apologize that parts of it
  26.    may be less intelligible than possible in HTML. Please refer to the
  27.    HTML version at http://sunsite.unc.edu/javafaq/javafaq.html.
  28.    
  29.    The only official mirrors of this site are at the other sunsites. If
  30.    the URL where you found this file is not a sunsite, then this is an
  31.    illegal mirror copy and is likely to be out of date. Please refer to
  32.    the official site instead.
  33.    
  34.    This document is Copyright 1995-1997 by Elliotte Rusty Harold. For
  35.    information about reproduction, redistribution and other such rights
  36.    please see the end of this file.
  37.    
  38. What's New
  39.  
  40.    
  41.    
  42.    Question 4.10: How do I load and display formatted HTML?
  43.    
  44.    I've added some info about Sun's HotJava HTML bean.
  45.    
  46.    Question 8.4: How do I format numbers like C's printf()?
  47.    
  48.    I've added some info about the java.text package.
  49.    
  50.    I've also added the following two questions:
  51.    
  52.      * 5.5: How can I make my applets work well on multiple browsers and
  53.        virtual machines?
  54.      * 14.3: Disassembly, Decompilation, and Obfuscation
  55.        
  56.    For the most part, this FAQ list covers Java 1.0.2. I have begun the
  57.    slow process of converting this list over to Java 1.1. I am aware of
  58.    the changes in Java 1.1 and will incorporate them as time permits.
  59.    Please don't send me email pointing out errors or omissions that are
  60.    only relevant to 1.1. I am fully cognizant of these.
  61.    
  62. Table of Contents
  63.  
  64.      * What's New
  65.      * Table of Contents
  66.      * 1: What is Java?
  67.           + 1.1: Where did Java come from?
  68.           + 1.2: Doesn't the World Wide Web have something to do with
  69.             this?
  70.           + 1.3: What platforms does Java run on?
  71.           + 1.4: Do I need to know C++ to learn Java?
  72.           + 1.5: Where does Javascript fit in?
  73.           + 1.6: What's the difference between an application and an
  74.             applet?
  75.      * 2: What other Java Resources are available?
  76.           + 2.1Web Sites
  77.           + 2.2: Mailing Lists
  78.           + 2.3: Newsgroups
  79.           + 2.4: Books
  80.      * 3: Java for C++ programmers
  81.           + 3.1: Data Types
  82.           + 3.2: Control Statements
  83.           + 3.3: Command Line Arguments
  84.           + 3.4: Comments
  85.           + 3.5: Classes
  86.           + 3.6: How is Java unlike C++?
  87.      * 4: How Do I...
  88.           + 4.1: Make a linked list without pointers?
  89.           + 4.2: How do I scanf, readln, etc. in Java?
  90.           + 4.3: How do I convert strings to numbers?
  91.           + 4.4: How Do I Call C Code from Java?
  92.           + 4.5: How Do I Call Java from C?
  93.           + 4.6: How do you do multiple inheritance?
  94.           + 4.7: Can I write objects to and read objects from a file or
  95.             other stream?
  96.           + 4.8: How do I call the native API from Java?
  97.           + 4.9: How do I pass a function pointer to a method?
  98.           + 4.10: How do I load and display formatted HTML?
  99.           + 4.11: How do I play a sound in an application?
  100.      * 5: Programming Applets
  101.           + 5.1: Can applets communicate with each other?
  102.           + 5.2: Can applets launch programs on the server?
  103.           + 5.3: Can applets launch programs on the client?
  104.           + 5.4: Can I record audio from an applet?
  105.           + 5.5: How can I make my applets work well on multiple browsers
  106.             and virtual machines?
  107.      * 6: Language Issues
  108.           + 6.1: What does it mean that a class or member is "final"?
  109.           + 6.2: What does it mean that a method or field is "static"?
  110.           + 6.3: What does it mean that a method or class is abstract?
  111.           + 6.4: What's an interface?
  112.           + 6.5: Why doesn't Java include insert your favorite feature
  113.             here?
  114.           + 6.6: Is Java CORBA compliant?
  115.           + 6.7: Can I cast an int to an Integer? a float to a Float?
  116.           + 6.8: How do I version a class?
  117.           + 6.9: Why isn't there operator overloading?
  118.           + 6.10: Does Java have pointers?
  119.           + 6.11: Does Java pass method arguments by value or by
  120.             reference?
  121.           + 6.12: Are there parameterized types (templates)?
  122.           + 6.13: How does garbage collection work?
  123.           + 6.14: PERFORM and BECOME
  124.      * 7: java.awt
  125.           + 7.1: What Does AWT Stand For?
  126.           + 7.2: What are peer "classes"?
  127.           + 7.3: Can you explain how events are passed?
  128.           + 7.4: Clipping
  129.           + 7.5: How do I change the thickness of the line?
  130.           + 7.6: What fonts does Java support?
  131.      * 8: java.io
  132.           + 8.1:How do I read data from a file?
  133.           + 8.2: How do I write data to a file?
  134.           + 8.3: How do I append data to a file?
  135.           + 8.4: How do I format numbers like C's printf()?
  136.      * 9: java.net
  137.           + 9.1: How do I convert a numeric IP address like 199.1.32.90
  138.             into a host name like star.blackstar.com?
  139.           + 9.2: How can a Java program talk to a CGI program?
  140.           + 9.3: How can an applet send email?
  141.           + 9.4: How can I use ICMP in Java?
  142.           + 9.5: How do I make Java work with a proxy server?
  143.      * 10: java.util
  144.           + 10.1: How random is Random()?
  145.           + 10.2: How do I generate a random integer between a and b?
  146.      * 11: Common Errors and Problems
  147.           + 11.1: How Can I Avoid Flicker in an Applet?
  148.           + 11.2: Can you explain CLASSPATH?
  149.           + 11.3: Why won't my audio clip play?
  150.           + 11.4: When I load the page Netscape gives me a
  151.             java.lang.ClassFormatError.
  152.           + 11.5: Netscape gives me "Applet Not Initialized Error"
  153.           + 11.6: Other Netscape Problems
  154.           + 11.7: I keep getting access privilege violations, " Java
  155.             tried to read file foo.class in directory bar."
  156.           + 11.8: javac keeps insisting that it can't find the right
  157.             constructor function in my class, but I'm sure it's in a
  158.             file I imported. Why is it even looking in my class instead
  159.             of the imported file?
  160.           + 11.9: NullPointerExceptions with arrays of objects
  161.           + 11.10: Can't make static reference to method type myMethod in
  162.             class myClass
  163.           + 11.11: Why do I have trouble when using == to compare
  164.             Strings?
  165.      * 12: Security
  166.           + 12.1: System Level Security
  167.           + 12.2: User Level Security
  168.      * 13: Tools
  169.           + 13.1: IDE
  170.           + 13.2: Debugger
  171.           + 13.3: Editors
  172.           + 13.4: YACC grammar
  173.           + 13.5: Profilers
  174.      * 14: The Java Virtual Machine and Byte Code
  175.           + 14.1: Can I program directly in byte code?
  176.           + 14.2: Optimizing Java
  177.           + 14.3: Disassembly, Decompilation, and Obfuscation
  178.      * 15: Legal Issues
  179.      * 16: FAQ's about the FAQ
  180.           + 16.1: Who is this Elliotte guy, and just what qualified him
  181.             to write a Java FAQ anyway?
  182.           + 16.2: Why don't you include X in your FAQ?
  183.           + 16.3: This is really cool. Can I republish or translate it?
  184.             
  185. 1: What is Java?
  186.  
  187.    Java, formerly known as oak, is an object-oriented programming
  188.    language developed by Sun. It shares many superficial similarities
  189.    with C, C++, and Objective C (for instance for loops have the same
  190.    syntax in all four languages); but it is not based on any of those
  191.    languages, nor have efforts been made to make it compatible with them.
  192.    
  193.    Java is sometimes referred to as C++ ++ --. The language was
  194.    originally created because C++ proved inadequate for certain tasks.
  195.    Since the designers were not burdened with compatibility with existing
  196.    languages, they were able to learn from the experience and mistakes of
  197.    previous object-oriented languages. They added a few things C++
  198.    doesn't have like garbage collection and multithreading; and they
  199.    threw away C++ features that had proven to be better in theory than in
  200.    practice like multiple inheritance and operator overloading. (There's
  201.    still argument over whether they made the right choices. I tend to
  202.    think they were correct to throw out operator overloading and probably
  203.    correct to throw out multiple inheritance. For now let's just say that
  204.    neither choice is likely to be reviewed soon.)
  205.    
  206.    Even more importantly Java was designed from the ground up to allow
  207.    for secure execution of code across a network, even when the source of
  208.    that code was untrusted and possibly malicious. This required the
  209.    elimination of more features of C and C++. Most notably there are no
  210.    pointers in Java. Java programs cannot (at least in theory) access
  211.    arbitrary addresses in memory.
  212.    
  213.    Furthermore Java was designed not only to be cross-platform in source
  214.    form like C, but also in compiled binary form. Since this is frankly
  215.    impossible across processor architectures, Java is compiled to an
  216.    intermediate byte-code which is interpreted on the fly by the Java
  217.    interpreter. Thus to port Java programs to a new platform all that is
  218.    needed is a port of the interpreter and a few native code libraries.
  219.    
  220.     Finally Java was designed to make it a lot easier to write bug free
  221.    code. Shipping C code has, on average, one bug per 55 lines of code.
  222.    About half of these bugs are related to memory allocation and
  223.    deallocation. Thus Java has a number of features to make bugs less
  224.    common:
  225.      * Strong Typing
  226.      * No unsafe constructs
  227.      * The language is small so its easy to become fluent.
  228.      * The language is easy to read and write. Obfuscated Java isn't
  229.        nearly as common as obfuscated C.
  230.      * There are no undefined or architecture dependent constructs.
  231.      * Java is object oriented so reuse is easy.
  232.      * Java has concurrency.
  233.        
  234.   1.1: WHERE DID JAVA COME FROM?
  235.   
  236.    In the late 1970's Bill Joy thought about doing a language that would
  237.    merge the best features of MESA and C. However other projects (like
  238.    cofounding Sun) intervened. In the late 1980's he got Sun's engineers
  239.    started on a complete revision of the UNIX operating system that
  240.    involved merging SunOS4.x with AT&T's SYSVR4.
  241.    
  242.    In 1989 Joy sold his Sun stock, invested heavily in Microsoft and
  243.    moved out of mainstream Sun to Aspen, Colorado. By the early 90's Bill
  244.    was getting tired of huge programs. He decided that he wanted to be
  245.    able to write a 10,000 line program that made a difference. In late
  246.    1990 Bill wrote a paper called Further which outlined his pitch to Sun
  247.    engineers that they should produce an object environment based on C++.
  248.    Today Joy freely admits that C++ was too complicated and wasn't up to
  249.    the job.
  250.    
  251.    Around this time James Gosling (of emacs fame) had been working for
  252.    several months on an SGML editor called "Imagination" using C++. The
  253.    Oak language (now Java) grew out of Gosling's frustration with C++ on
  254.    his "Imagination" project.
  255.    
  256.    Patrick Naughton, then of Sun, now vice-president of technology at
  257.    StarWave, started the Green Project on December 5th, 1990. Naughton
  258.    defined the project as an effort to "do fewer things better". That
  259.    December he recruited Gosling and Mike Sheridan to help start the
  260.    project. Joy showed them his Further paper, and work began on graphics
  261.    and user interface issues for several months in C.
  262.    
  263.    In April of 1991 the Green Project (Naughton, Gosling and Sheridan)
  264.    settled on smart consumer electronics as the delivery platform, and
  265.    Gosling started working in earnest on Oak. Gosling wrote the original
  266.    compiler in C; and Naughton, Gosling and Sheridan wrote the
  267.    runtime-interpreter, also in C. Oak was running its first programs in
  268.    August of 1991. Joy got his first demos of the system that winter,
  269.    when Gosling and Naughton went skiing at Joy's place in Aspen.
  270.    
  271.    By the fall of 1992 "*7", a cross between a PDA and a remote control,
  272.    was ready This was demoed to Scott McNealy, Sun's president, in
  273.    October. He was blown away. Following that the Green Project was set
  274.    up as First Person Inc., a wholly owned Sun subsidiary.
  275.    
  276.    In early 1993 the Green team heard about a Time-Warner request for
  277.    proposal for a settop box operating system. First Person quickly
  278.    shifted focus from smart consumer electronics (which was proving to be
  279.    more hype than reality) to the set-top box OS market, and placed a bid
  280.    with Time-Warner.
  281.    
  282.    Fortuitously, Sun lost the bid. The Time-Warner project went nowhere,
  283.    the same place it probably would have gone if Sun had won the bid.
  284.    First Person continued work on settop boxes until early 1994, when it
  285.    concluded that like smart consumer electronics settop boxes were more
  286.    hype than reality.
  287.    
  288.    Without a market to be seen First Person was rolled back into Sun in
  289.    1994. However around this time it was realized that the requirements
  290.    for smart consumer electronics and settop box software (small,
  291.    platform independent secure reliable code) were the same requirements
  292.    for the nascent web.
  293.    
  294.    For a third time the project was redirected, this time at the web. A
  295.    prototype browser called WebRunner was written by Patrick Naughton in
  296.    one weekend of inspired hacking. After additional work by Naughton and
  297.    Jonathan Payne this browser became HotJava. The rest, as they say, is
  298.    history.
  299.    
  300.    Information in this section is primarily based on the first hand
  301.    accounts of Bill Joy and Patrick Naughton (which don't always agree).
  302.    No doubt other people have still different memories of what occurred.
  303.    If you've got any more first hand information about what went on in
  304.    the Green project I'd like to hear from you.
  305.    
  306.   1.2: DOESN'T THE WORLD WIDE WEB HAVE SOMETHING TO DO WITH THIS?
  307.   
  308.    Not necessarily. Java is a programming language. When work began on
  309.    what has become Java, the World Wide Web was just getting started at
  310.    CERN; and Mosaic wasn't even a glint in Marc Andreesen's eye. The
  311.    original use of the Java language (settop boxes) required security and
  312.    the ability to execute code from untrusted hosts. It turns out these
  313.    are virtually the same requirements for allowing people to download
  314.    and run programs from the Web. No other language has the built-in
  315.    security of Java. The key here is the security features. The
  316.    object-oriented nature of Java is secondary, and mainly reflects the
  317.    preferences and prejudices of the developers who set out to write a
  318.    secure language. The C-like syntax of the language is even less
  319.    crucial.
  320.    
  321.    At the lowest level the advantage of Java to the web is that it
  322.    provides a secure, cross-platform way for code to be executed. At a
  323.    somewhat higher level Java adds several features to existing web
  324.    sites:
  325.    
  326.    Arbitrary Graphics
  327.           Java lets the server draw pictures in a window on the client.
  328.           In theory this allows a web page to do anything a regular
  329.           program can do by drawing in a window.
  330.           
  331.    Arbitrary Data Types
  332.           In practice rather than using graphics primitives to create
  333.           your desired web page you'd use a graphics program to draw the
  334.           page and then write a program that could read and display the
  335.           file formats of that program. Java lets you write content
  336.           handlers that display any particular data format. This way you
  337.           can download your data and your data display program rather
  338.           than downloading a bitmapped snapshot of the display. People
  339.           are already using this to add sound and animation to web pages.
  340.           Rather than having to download a file and spawn an external
  341.           viewer, the viewer is included with the data; and the data is
  342.           displayed right on the page.
  343.           
  344.    Less Load On The Server
  345.           CPU intensive cgi-bin scripts place a large load on a server,
  346.           particularly at busy sites. With Java you can off-load the
  347.           calculations to the client's PC. I've written an applet that
  348.           calculates all possible ram configurations for a given Mac
  349.           model. However on models with many memory slots the sheer
  350.           number of permutations can tie up even a fast machine for
  351.           several hours. Publishing this as a cgi-bin would bring my
  352.           server to its knees, but by publishing it as a Java applet I
  353.           can distribute the load across all the machines that want to
  354.           run it.
  355.           
  356.    More User Interaction
  357.           Finally Java allows for more interaction with the user. Java
  358.           not only allows you to paint arbitrary data on the screen. It
  359.           also allows you to collect input from the user in the form of
  360.           mouse clicks, keystrokes and the like. This lets you put almost
  361.           any application on your web page that doesn't require disk
  362.           access.
  363.           
  364.   1.3: WHAT PLATFORMS DOES JAVA RUN ON?
  365.   
  366.    Sun has made a Java Development Kit (JDK) available for Sparc and X86
  367.    Solaris, Windows NT and Windows 95 Intel. The JDK is free, and most
  368.    third party ports are based on this.
  369.    
  370.    Sun also published a 1.0.2 JDK for MacOS 7.5 on PowerMacs and 68030
  371.    (25 MHz and faster) and 68040 Macs. However it's dropped development
  372.    for Macs in favor of Apple's own Macintosh Runtime for Java (MRJ)
  373.    which is a better option for Mac users. Currently MRJ supports Java
  374.    1.0. Java 1.1 support is promised soon.
  375.    
  376.    SGI's port of Sun's JDK 1.1.x to IRIX 5.3, 6.2, 6.3, and 6.4 is
  377.    available at http://www.sgi.com/Fun/Free_webtools.html. An IRIX port
  378.    of JDK 1.0 has mostly been completed by Simon Leinen.
  379.    
  380.    A Linux port is in fairly good shape. See
  381.    http://java.blackdown.org/java-linux.html.
  382.    
  383.    IBM has ported Java to Windows 3.1, OS/2, and AIX. It is working on
  384.    ports for MVS and OS/400. See
  385.    http://ncc.hursley.ibm.com/javainfo/hurindex.html .
  386.    
  387.    The OSF has ported the JDK 1.0.2 to Unixware, the Bull Estrella or
  388.    other PowerPC running AIX4.1, X86 running DASCOM OSF/1 , the Digital
  389.    Alpha running Digital UNIX 3.2, the HP700 series running HPUX 10.x,
  390.    the NCR Globalyst (Pentium) running UNIX SysV, and Sony NEWS (MIPS)
  391.    running Sony NEWS 6.1.1. See http://www.osf.org/mall/web/JDK/.
  392.    
  393.    Other ports are underway for Nextstep, SunOS 4.1, the Amiga and
  394.    possibly other platforms.
  395.    
  396.    In the past new versions of Java have most often been made available
  397.    first for Solaris. If you have to have the latest version as soon as
  398.    it's released, or if you're developing "Bet your company" applications
  399.    with Java, you should probably be running Solaris on a SparcStation.
  400.    Otherwise, if you just want to learn the language, you can get away
  401.    with an Intel based Windows 95 or NT machine with a lot of RAM.
  402.    
  403.    Netscape 2.0 and later plays Java 1.0 applets on Windows NT, Windows
  404.    95, Solaris, SunOS 4.1, Linux and most other Unix platforms. Netscape
  405.    3.0 for the Mac also supports Java 1.0. Netscape 4.0 and earlier and
  406.    Internet Explorer 3.0 and earlier do not support Java 1.1 to any
  407.    significant extent, only Java 1.0. The only web browser that really
  408.    supports Java 1.1 is Sun's HotJava.
  409.    
  410.    Netscape 2.0 can even compile Java programs. (Netscape 3.0 cannot).
  411.    
  412.    First download the classes.zip file from the Solaris distribution of
  413.    the JDK. (You have to download the entire JDK. You can't get just the
  414.    classes.zip file.) Next set your CLASSPATH environment variable to
  415.    include the classes.zip file. For example, on Unix, if you put the
  416.    file in /usr/local/lib/classes.zip, then you would set it like this:
  417.    
  418. sh: % CLASSPATH=$CLASSPATH:/usr/local/lib/classes.zip
  419. csh: % setenv CLASSPATH "$CLASSPATH:/usr/local/lib/classes.zip"
  420.  
  421.    You'll probably want to put this line in your .login or .cshrc file.
  422.    Of course you'll need to adjust this to match where you've installed
  423.    these files and to add any other classes you use. Finally you compile
  424.    programs from the command line like this:
  425.    
  426. % netscape -java sun.tools.javac.Main HelloWorld.java
  427.  
  428.    You can always alias netscape -java sun.tools.javac.Main to just javac
  429.    to make this more transparent.
  430.    
  431.    You can also run command-line programs that don't use the AWT in the
  432.    same way, like this:
  433.    
  434. % netscape -java HelloWorld.class
  435.  
  436.    You can't use netscape -java to run programs that use the AWT, but you
  437.    can of course play applets in Netscape..
  438.    
  439.   1.4: DO I NEED TO KNOW C++ TO LEARN JAVA?
  440.   
  441.    No. Java is in fact a much easier language to learn than C++.
  442.    
  443.    A little further out in left field, it isn't even necessary to know
  444.    Java to write Java programs. Intermetrics is beta testing an ADA-95 to
  445.    Java byte code compiler. Other such cross-compilers are probably
  446.    possible including ANSI Fortran-77, COBOL, and Basic. However the one
  447.    most people probably want, a C/C++ to Java byte code compiler, is
  448.    probably not possible due to Java's lack of pointers.
  449.    
  450.   1.5: WHERE DOES JAVASCRIPT FIT IN?
  451.   
  452.    To quote from p. 31 of my book, The Java Developer's Resource,
  453.    
  454.      Java and JavaScript are about as closely related as the Trump Taj
  455.      Mahal in Atlantic City is to the Taj Mahal in India. In other words
  456.      Java and JavaScript both have the word Java in their names.
  457.      JavaScript is a programming language from Netscape which is
  458.      incorporated in their browsers. It is superficially similar to Java
  459.      in the same way C is similar to Java but differs in all important
  460.      respects.
  461.      
  462.   1.6: WHAT'S THE DIFFERENCE BETWEEN AN APPLICATION AND AN APPLET?
  463.   
  464.    This question can be answered on many levels. Technically an
  465.    application is a Java class that has a main() method. An applet is a
  466.    Java class which extends java.applet.Applet. A class which extends
  467.    java.applet.Applet and also has a main() method is both an application
  468.    and an applet.
  469.    
  470.    More generally and less technically an application is a stand-alone
  471.    program, normally launched from the command line, and which has more
  472.    or less unrestricted access to the host system. An applet is a program
  473.    which is run in the context of an applet viewer or web browser, and
  474.    which has strictly limited access to the host system. For instance an
  475.    applet can normally not read or write files on the host system whereas
  476.    an application normally can.
  477.    
  478.    The actions of both applets and applications, however, can be
  479.    controlled by SecurityManager objects. If you can change the
  480.    SecurityManager that's used you can change what an applet or an
  481.    application is and is not allowed to do. Thus these are not hard and
  482.    fast differences, though this is normally how they separate out in
  483.    practice.
  484.    
  485. 2 What other Java Resources are available?
  486.  
  487.   2.1WEB SITES
  488.   
  489.    The key site for Java information is http://www.javasoft.com/. This is
  490.    Sun's official site for Java, and contains the latest published
  491.    version of all official Java information. The most important page on
  492.    this site is the Documentation page at http://www.javasoft.com/doc/.
  493.    Most of the other pages are linked off of this page or its children.
  494.    
  495.    For many more web sites see the Cafe au Lait links page at
  496.    http://sunsite.unc.edu/javafaq/links.html.
  497.    
  498.   2.2: MAILING LISTS
  499.   
  500.    There are over sixty different Java related mailing lists. A
  501.    more-or-less complete list is at the Cafe Au Lait mailing list page at
  502.    http://sunsite.unc.edu/javafaq/mailinglists.html.
  503.    
  504.   2.3: NEWSGROUPS
  505.   
  506.    alt.www.hotjava
  507.           A newsgroup for the discussion of the HotJava browser.
  508.           
  509.    comp.lang.java.announce
  510.           A newsgroup for announcements that may be of interest to Java
  511.           developers. See
  512.           http://www.cs.latrobe.edu.au/~leachbj/clj.announce/guidelines
  513.           .html for the ridiculously complicated submission guidelines
  514.           and submission address.
  515.           
  516.    comp.lang.java.programmer
  517.           A newsgroup for the discussion of the Java language.
  518.           
  519.    comp.lang.java.machine
  520.           Technical issues about Java not related directly to
  521.           programming, including virtual machines, byte code, classfile
  522.           format, performance and optimization, possible extensions,
  523.           porting, native methods and interfacing Java with other
  524.           languages.
  525.           
  526.    comp.lang.java.security
  527.           Discussion concerning any of Java's security features such as
  528.           byte code verification, SecurityManagers, class loaders,
  529.           public-key encryption and authentication of classes, holes in
  530.           the security model, and similar topics.
  531.           
  532.    comp.lang.java.help
  533.           This group is for end-users of Java systems, not programmers.
  534.           It deals with installation problems, CLASSPATH problems, the
  535.           availability of ports to specific platforms, and the like.
  536.           Subject lines should include the platform that the problem
  537.           occurs on, and the browser version, for example MacOS 7.5
  538.           Netscape 3.0.
  539.           
  540.    comp.lang.java.beans
  541.           The JavaBeans component software API
  542.           
  543.    comp.lang.java.databases 
  544.           Java and databases, including middleware like java.sql, JDBC,
  545.           ODBC, and Java based databases like jDB.
  546.           
  547.    comp.lang.java.gui
  548.           The AWT and other GUI enrvironments: windows, dialogs, menus,
  549.           components, buttons, radio buttons, printing, cut and paste,
  550.           etc.
  551.           
  552.    comp.lang.java.softwaretools
  553.           Integrated Development Environments (IDEs), web browsers,
  554.           compilers, applet viewers, Rapid Application Development (RAD)
  555.           tools, class browsers, visual interface builders, and other
  556.           tools.
  557.           
  558.   2.4: BOOKS
  559.   
  560.    As of March, 1997 I recommend four books in particular for those
  561.    learning the language. The first is my own book, The Java Developer's
  562.    Resource, ISBN: 0-13-570789-7, $26.95 from Prentice Hall. This is an
  563.    introduction to Java 1.0 for programmers, regardless of previous
  564.    experience with C or OOP. It should be available in most bookstores
  565.    that stock computer books as well as from amazon.com,
  566.    http://www.amazon.com/exec/obidos/ISBN=0135707897/
  567.    
  568.    The second book I recommend is Java in a Nutshell: A Desktop Quick
  569.    Reference for Java Programmers by David Flanagan from O'Reilly &
  570.    Associates, Inc., ISBN: 1-56592-262-X, $19.95 (the tiger book). This
  571.    is an excellent introduction to Java for C and C++ programmers and an
  572.    excellent reference for everyone.
  573.    
  574.    For people with no prior experience in programming I recommend Kris
  575.    Jamsa's Java Now!, ISBN: 1-884133-30-4, $16.95, Jamsa Press.
  576.    
  577.    None of these books cover Java 1.1. In fact as of this writing, few
  578.    books truly cover Java 1.1 though several claim to. The best of the
  579.    lot as of this writing seems to be Rogers Cadenhead's Teach Yourself
  580.    Java 1.1 Programming in 24 Hours from Sams.net, ISBN 1-57521-270-6.
  581.    This is a decent book introducing Java 1.1 programming to
  582.    non-programmers. However it's quite basic, and coverage of the AWT is
  583.    very limited.
  584.    
  585.    For details about these and many more books see the Cafe au Lait books
  586.    page at http://sunsite.unc.edu/javafaq/books.html
  587.    
  588. 3: Java for C++ programmers
  589.  
  590.    In the large Java looks like Smalltalk. In the small it looks like C.
  591.    The syntax of Java is deliberately similar to C. If you know C you
  592.    already know large chunks of Java. Here, in brief, is Java syntax for
  593.    C programmers:
  594.    
  595.   3.1: DATA TYPES
  596.   
  597.    Java's primitive data types are very similar to those of C. (The
  598.    boolean type has been added.) However the implementation of the data
  599.    types has been substantially cleaned up in several ways.
  600.    
  601.     1. Where C and C++ leave a number of issues to be machine and
  602.        compiler dependent (for instance the size of an int) Java
  603.        specifies everything.
  604.        
  605.     2. Java prevents casting between arbitrary variables. Only casts
  606.        between numeric variables and between sub and superclasses of the
  607.        same object are allowed.
  608.        
  609.     3. All numeric variables in Java are signed.
  610.        
  611.    
  612.    
  613.    Here are the detailed primitive data types:
  614.    
  615.    boolean
  616.           1-bit. May take on the values true and false only.
  617.           
  618.           true and false are defined constants of the language and are
  619.           not the same as True and False, TRUE and FALSE, zero and
  620.           nonzero, 1 and 0 or any other numeric value. Booleans may not
  621.           be cast into any other type of variable nor may any other
  622.           variable be cast into a boolean.
  623.           
  624.    byte
  625.           1 signed byte (two's complement). Covers values from -128 to
  626.           127.
  627.           
  628.    short
  629.           2 bytes signed (two's complement), -32,768 to 32,767
  630.           
  631.    int
  632.           4 bytes, signed (two's complement). -2,147,483,648 to
  633.           2,147,483,647. Like all numeric types ints may be cast into
  634.           other numeric types (byte, short, long, float, double). When
  635.           lossy casts are done (e.g. int to byte) the conversion is
  636.           done modulo the length of the smaller type.
  637.           
  638.    long
  639.           8 bytes signed (two's complement). Ranges from
  640.           -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
  641.           
  642.    float
  643.           4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45
  644.           to 3.40282346638528860e+38 (positive or negative).
  645.           
  646.           Like all numeric types floats may be cast into other numeric
  647.           types (byte, short, long, int, double). When lossy casts to
  648.           integer types are done (e.g. float to short) the fractional
  649.           part is truncated and the conversion is done modulo the length
  650.           of the smaller type.
  651.           
  652.    double
  653.           8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d
  654.           to 1.79769313486231570e+308d (positive or negative).
  655.           
  656.    char
  657.           2 unsigned bytes, Unicode.
  658.           
  659.           Chars are not the same as bytes, ints, shorts or Strings.
  660.           
  661.           sizeof isn't necessary in Java because all sizes are precisely
  662.           defined. i.e. an int is always 4 bytes. This may not seem to be
  663.           adequate when dealing with objects that aren't base data types.
  664.           However even if you did know the size of a particular object,
  665.           you couldn't do anything with it anyway. You cannot convert an
  666.           arbitrary object into bytes and back again.
  667.           
  668.           Strings are a reference or object type, that is a instances of
  669.           the class java.lang.String. They are not null terminated and
  670.           are not the same as an array of chars.
  671.           
  672.           Arrays are also objects. Multidimensional arrays are created
  673.           via arrays of arrays.
  674.           
  675.   3.2: CONTROL STATEMENTS
  676.   
  677.    Java contains if, else, for, while, do while and switch statements.
  678.           The syntax is identical to C's. However all condition tests
  679.           must return boolean values. Since non-boolean assignment
  680.           statements and arithmetic statements do not return a boolean
  681.           value, some of the more obfuscated condition tests in C are
  682.           prohibited.
  683.           
  684.   3.3: COMMAND LINE ARGUMENTS
  685.   
  686.    Command line arguments are like C's except that argv has become a
  687.           string array commonly called args and args[0] is the first
  688.           command line argument, not the name of the program. The other
  689.           arguments are all shifted one to the left from where they'd be
  690.           in C or C++.
  691.           
  692.   3.4: COMMENTS
  693.   
  694.    Java supports both the /* This is a comment */ comment from C and the
  695.           // This is a C++ comment
  696.           comment from C++.
  697.           
  698.           However comments that begin with a /** are special. These
  699.           comments should only be used before a method or class
  700.           declaration. They indicate that the comment should be included
  701.           in automatically generated documentation for that declaration.
  702.           
  703.   3.5: CLASSES
  704.   
  705.    Java does not support multiple inheritance.
  706.           
  707.           Superclasses of a class are indicated with the extends keyword
  708.           rather than with a :.
  709.           
  710.           Methods must be defined inside the class to which they belong.
  711.           They may not be declared inside the class and defined outside
  712.           the class as is common in C++.
  713.           
  714.   3.6: HOW IS JAVA UNLIKE C++?
  715.   
  716.    Two classes of language features have been removed from C++ to make it
  717.           Java. These are those language features which make C++ unsafe
  718.           and those which make it hard to read.
  719.           
  720.           Features removed that make Java easier to read and understand
  721.           than C++ include #define, typedef, operator overloading, enum,
  722.           unions and structs.
  723.           
  724.           The main feature removed to make Java safer and more robust
  725.           than C++ is pointer arithmetic.
  726.           
  727.           Other features removed include global variables, standalone
  728.           functions (everything is a method), friend functions
  729.           (Everything in a package is a friend of everything else in the
  730.           package.) and non-virtual functions.
  731.           
  732.           A number of features have been added to Java to make it safer
  733.           including true arrays with bounds checking, garbage collection,
  734.           concurrency, interfaces (from Objective C) and packages. There
  735.           is no need to explicitly allocate or free memory in Java.
  736.           
  737. 4: How Do I...
  738.  
  739.   4.1: MAKE A LINKED LIST WITHOUT POINTERS?
  740.   
  741.    Short answer: Use the Vector class in java.util. It can do anything a
  742.           linked list can do and a little more and saves you a lot of
  743.           coding which, after all, is the point of OOP and the class
  744.           library. However it is array based so insertions or deletions
  745.           from the middle of a Vector are not as efficient as with a true
  746.           linked list.
  747.           
  748.           Long answer: Object variables in Java are all references. A
  749.           reference acts like a pointer in most other languages. (Though
  750.           they're handles, not pointers, in most Java implementations.
  751.           The notable exception is Microsoft's.) The main difference is
  752.           that you can't do pointer arithmetic on references. Therefore
  753.           wherever you'd use a pointer to an object in C++, in Java you
  754.           should just use the object itself.
  755.           
  756.           On the other hand the primitive data types (int, float, double,
  757.           char, byte, short, long and boolean) are not references. If you
  758.           want to get a reference to one of these you need to wrap it in
  759.           a class first. Java provides ready-made type-wrapper classes in
  760.           the java.lang package for Boolean, Character, Integer, Double,
  761.           Float, and Long. Bytes and shorts can be stored in the Integer
  762.           class as well. Java 1.1 adds Byte, Short, and Void classes too.
  763.           
  764.   4.2: HOW DO I SCANF, READLN, ETC. IN JAVA?
  765.   
  766.    Java has no exact equivalent to C's scanf(), fscanf() and sscanf()
  767.           functions, Pascal's read() and readln() function, or Fortran's
  768.           READ* function. In particular there's no one method that lets
  769.           you get input from the user as a numeric value.
  770.           
  771.           However, roughly equivalent functionality is scattered across
  772.           several classes. You first read an input line into a String
  773.           using DataInputStream.readline() or BufferedReader (in Java
  774.           1.1)
  775.           
  776.           Next use the StringTokenizer class in java.util to split the
  777.           String into tokens. By default StringTokenizer splits on white
  778.           space (spaces, tabs, carriage returns and newlines), but this
  779.           is user definable.
  780.           
  781.           For example,
  782.           
  783. import java.util.StringTokenizer;
  784.  
  785. class STTest {
  786.  
  787.   public static void main(String args[]) {
  788.  
  789.     String s = "9 23 45.4 56.7";
  790.  
  791.     StringTokenizer st = new StringTokenizer(s);
  792.     while (st.hasMoreTokens()) {
  793.       System.out.println(st.nextToken());
  794.     }
  795.  
  796.   }
  797.  
  798. }
  799.  
  800.    prints the following output:
  801.           
  802.  
  803. 9
  804. 23
  805. 45.4
  806. 56.7
  807.  
  808.    Finally you convert these tokens into numbers using the type wrapper
  809.           classes as described in the next question.
  810.           
  811.   4.3: HOW DO I CONVERT STRINGS TO NUMBERS?
  812.   
  813.    You can convert strings into numbers using the Integer, Float, Double
  814.           and Long type wrapper classes as indicated by the following
  815.           code snippet:
  816.           
  817. class ConvertTest {
  818.  
  819.   public static void main (String args[]) {
  820.  
  821.     String str;
  822.  
  823.     str = "25";
  824.  
  825.     int i = Integer.valueOf(str).intValue();
  826.     System.out.println(i);
  827.     long l = Long.valueOf(str).longValue();
  828.     System.out.println(l);
  829.  
  830.     str = "25.6";
  831.  
  832.     float f = Float.valueOf(str).floatValue();
  833.     System.out.println(f);
  834.     double d = Double.valueOf(str).doubleValue();
  835.     System.out.println(d);
  836.  
  837.   }
  838.  
  839. }
  840.  
  841.    There are no equivalent Short and Byte classes in Java 1.0. There are
  842.           in Java 1.1. For shorts and bytes use the Integer class but use
  843.           the byteValue() or shortValue() methods instead.
  844.           
  845.   4.4: HOW DO I CALL C CODE FROM JAVA?
  846.   
  847.    First of all for security reasons you can only call external code from
  848.           an application. You cannot call external code from an applet.
  849.           (Otherwise all the security would go out the window.)
  850.           Furthermore all code you write in this way will be
  851.           non-portable. If these aren't problems for you, check out javah
  852.           in the JDK 1.0 or the Java Native Interface in JDK 1.1.
  853.           
  854.           Chapter 19 of my book Java Secrets discusses the Java Native
  855.           Interface in depth. (IDG Books, 1997, ISBN 0-764-58007-8,
  856.           http://www.amazon.com/exec/obidos/ISBN=0764580078/cafeaulaitA
  857.           /)
  858.           
  859.   4.5: HOW DO I CALL JAVA FROM C?
  860.   
  861.    Since Java is not as of yet a true compiled language, the only way to
  862.           call Java code from C in Java 1.0 is by using the system() call
  863.           (or your OS's equivalent) to execute the java interpreter with
  864.           appropriate command line arguments.
  865.           
  866.           In Java 1.1 the Java Native Method Interface in combination
  867.           with the Invocation API allows native applications to load and
  868.           access the Java virtual machine.
  869.           
  870.   4.6: HOW DO YOU DO MULTIPLE INHERITANCE?
  871.   
  872.    Java does not support multiple inheritance. Instead declare interfaces
  873.           for each additional class you want to inherit from, and
  874.           implement those interfaces in your subclass. For more details,
  875.           see question 6.1 below.
  876.           
  877.   4.7: CAN I WRITE OBJECTS TO AND READ OBJECTS FROM A FILE OR OTHER STREAM?
  878.   
  879.    In theory yes, but once again all the coding is up to you. There is no
  880.           general method for doing this in Java 1.0. The problem is made
  881.           harder by Java's security features that don't let you forge
  882.           arbitrary byte streams into objects.
  883.           
  884.           In Java 1.1 a serialization interface has been added to the
  885.           language. However only objects that explicitly implement the
  886.           java.io.Serializable interface can be serialized.
  887.           
  888.   4.8: HOW DO I CALL THE NATIVE API FROM JAVA?
  889.   
  890.    You can do this only in an application, not in an applet. You will
  891.           need to write some intermediary code in C or another
  892.           traditional language and call your C code from Java.
  893.           
  894.   4.9: HOW DO I PASS A FUNCTION POINTER TO A METHOD?
  895.   
  896.    Methods are not first class objects in Java. Only objects and
  897.           primitive data types can be passed to methods.
  898.           
  899.           Instead you should declare an interface which declares the
  900.           function you want to pass; for example
  901.           
  902. public interface Comparable {
  903.  
  904.   public abstract int compare(Object o1, Object o2);
  905.  
  906. }
  907.  
  908.    Then declare that your method takes an object of this type. For
  909.           example,
  910.           
  911.   public void sort(Object[] o, Comparable c) {
  912.  
  913.     boolean done = false;
  914.     while (!done) {
  915.       done = true;
  916.       for (int i = 0; i < o.length - 1; i++) {
  917.       if (c.compare(o[i], o[i+1]) < 0) {
  918.         swap(o[i], o[i+1]);
  919.         done = false;
  920.       }
  921.  
  922.     }
  923.  
  924.   }
  925.  
  926.    Each class you want to compare then needs its own class which
  927.           implements Comparable. For example,
  928.           
  929. public class StringCompare implements Comparable {
  930.  
  931.   public int compare(Object o1, Object o2) {
  932.  
  933.     String s1 = (String) o1;
  934.     String s2 = (String) o2;
  935.     return s1.compareTo(s2);
  936.  
  937.   }
  938.  
  939. }
  940.  
  941.    It helps that Object is a superclass for all object types.
  942.           
  943.   4.10: HOW DO I LOAD AND DISPLAY FORMATTED HTML?
  944.   
  945.    If you need to do this, you should probably be looking at JavaScript
  946.           instead of Java. It's possible in Java, but only with GREAT
  947.           difficulty. There is no simple answer at this point in time.
  948.           The problem is that Java does not contain a built-in HTML
  949.           rendering engine. You either need to generate the file on the
  950.           server, then load the URL of that file into the browser; or you
  951.           need to write a complete HTML parser and display engine.
  952.           
  953.           Recently Sun released the $195 payware HotJava HTML Component.
  954.           This is a Java bean which parses and renders HTML. In requires
  955.           Java 1.1 or later.
  956.           
  957.           There is at least one semi-free third party solution. Data
  958.           Technology's Ice Browser
  959.           (http://www.bgnett.no/datatech/ICEBrowser/index.html) can
  960.           handle most HTML 3.2 constructs, though I haven't had a chance
  961.           to test it personally yet. Ice Browser also requires Java 1.1.
  962.           
  963.   4.11: HOW DO I PLAY A SOUND IN AN APPLICATION?
  964.   
  965.    Java's audio support comes from the AppletContext class and the
  966.           AudioClip interface. Since applications don't have applet
  967.           contexts, they have no easy way to play audio clips. This is
  968.           supposed to be fixed in Java 1.2. In the meantime you have to
  969.           use undocumented classes in the sun packages. The following
  970.           example demonstrates:
  971.           
  972. import sun.audio.*;
  973. import java.awt.*;
  974. import java.io.*;
  975.  
  976.  
  977. public class SoundPlayer extends Frame implements FilenameFilter {
  978.  
  979.   Button openButton = new Button("Open");
  980.   Button playButton = new Button("Play");
  981.   Button loopButton = new Button("Loop");
  982.   Button stopButton = new Button("Stop");
  983.   Label filename = new Label("                   ");
  984.   File theFile = null;
  985.   AudioData theData = null;
  986.   InputStream nowPlaying = null;
  987.  
  988.   public SoundPlayer() {
  989.     super("Sound Player");
  990.     resize(300, 200);
  991.     Panel north = new Panel();
  992.     north.setLayout(new FlowLayout(FlowLayout.LEFT));
  993.     north.add(new Label("File: "));
  994.     north.add("North", filename);
  995.     add("North", north);
  996.     Panel south = new Panel();
  997.     south.add(openButton);
  998.     south.add(playButton);
  999.     south.add(loopButton);
  1000.     south.add(stopButton);
  1001.     add("South", south);
  1002.   }
  1003.  
  1004.   public static void main(String[] args) {
  1005.     SoundPlayer sp = new SoundPlayer();
  1006.     sp.show();
  1007.   }
  1008.  
  1009.   public void open() {
  1010.     FileDialog fd = new FileDialog(this, "Please select a .au file:");
  1011.     fd.setFilenameFilter(this);
  1012.     fd.show();
  1013.     try {
  1014.       theFile = new File(fd.getDirectory() + "/" + fd.getFile());
  1015.       if (theFile != null) {
  1016.         filename.setText(theFile.getName());
  1017.         FileInputStream fis = new FileInputStream(theFile);
  1018.         AudioStream as = new AudioStream(fis);
  1019.         theData = as.getData();
  1020.       }
  1021.     }
  1022.     catch (IOException e) {
  1023.       System.err.println(e);
  1024.     }
  1025.   }
  1026.  
  1027.   public void play() {
  1028.     stop();
  1029.     if (theData == null) open();
  1030.     if (theData != null) {
  1031.       AudioDataStream ads = new AudioDataStream(theData);
  1032.       AudioPlayer.player.start(ads);
  1033.       nowPlaying = ads;
  1034.     }
  1035.   }
  1036.  
  1037.   public void stop() {
  1038.     if (nowPlaying != null) {
  1039.       AudioPlayer.player.stop(nowPlaying);
  1040.       nowPlaying = null;
  1041.     }
  1042.   }
  1043.  
  1044.   public void loop() {
  1045.     stop();
  1046.     if (theData == null) open();
  1047.     if (theData != null) {
  1048.       ContinuousAudioDataStream cads = new ContinuousAudioDataStream(theData);
  1049.       AudioPlayer.player.start(cads);
  1050.       nowPlaying = cads;
  1051.     }
  1052.   }
  1053.  
  1054.   public boolean action(Event e, Object what) {
  1055.  
  1056.     if (e.target == playButton) {
  1057.       play();
  1058.       return true;
  1059.     }
  1060.     else if (e.target == openButton) {
  1061.       open();
  1062.       return true;
  1063.     }
  1064.     else if (e.target == loopButton) {
  1065.       loop();
  1066.       return true;
  1067.     }
  1068.     else if (e.target == stopButton) {
  1069.       stop();
  1070.       return true;
  1071.     }
  1072.  
  1073.     return false;
  1074.  
  1075.   }
  1076.  
  1077.   public boolean accept(File dir, String name) {
  1078.  
  1079.     name = name.toLowerCase();
  1080.     if (name.endsWith(".au")) return true;
  1081.     if (name.endsWith(".wav")) return true;
  1082.     return false;
  1083.  
  1084.   }
  1085.  
  1086. }
  1087.  
  1088.    This example is taken from Chapter 10 of Java Secrets, available from
  1089.           amazon
  1090.           (http://www.amazon.com/exec/obidos/ISBN=0764580078/cafeaulait
  1091.           A/) and various independent bookstores. It's published by IDG
  1092.           Books, ISBN number 0-764-58007-8. Chapters 8-17 cover various
  1093.           of the sun packages including sun.audio. (Chapters 1-7 cover
  1094.           the internals of Java like byte code and class files. Chapter
  1095.           19 and 20 cover platform dependent Java including native
  1096.           methods.)
  1097.           
  1098. 5: Programming Applets
  1099.  
  1100.   5.1: CAN APPLETS COMMUNICATE WITH EACH OTHER?
  1101.   
  1102.    At this point in time applets may communicate with other applets
  1103.           running in the same virtual machine. If the applets are of the
  1104.           same class, they can communicate via shared static variables.
  1105.           If the applets are of different classes, then each will need a
  1106.           reference to the same class with static variables. In any case
  1107.           the basic idea is to pass the information back and forth
  1108.           through a static variable.
  1109.           
  1110.           An applet can also get references to all other applets on the
  1111.           same page using the getApplets() method of
  1112.           java.applet.AppletContext. Once you've got a reference to an
  1113.           applet, you can communicate with it by using its public
  1114.           members.
  1115.           
  1116.           It is conceivable to have applets in different virtual machines
  1117.           that talk to a server somewhere on the Internet and store any
  1118.           data that needs to be serialized there. Then, when another
  1119.           applet needs this data, it could connect to this same server.
  1120.           Implementing this is non-trivial.
  1121.           
  1122.   5.2: CAN APPLETS LAUNCH PROGRAMS ON THE SERVER?
  1123.   
  1124.    Yes, using CGI. Any other implementation would be server dependent. Of
  1125.           course this requires a lot of coding and is non-trivial. A
  1126.           simple way to do this is not built into Java because that would
  1127.           require a special server. One of Java's strengths is that it is
  1128.           web server independent.
  1129.           
  1130.           A number of organizations have developed special http servers
  1131.           that allow applets or other clients to run Java programs on the
  1132.           server in a secure environment. Most notably Sun's Java Web
  1133.           Server implements a servlet interface for this purpose. The
  1134.           W3C's JigSaw implements a similar idea called resource objects.
  1135.           
  1136.   5.3: CAN APPLETS LAUNCH PROGRAMS ON THE CLIENT?
  1137.   
  1138.    Absolutely not. This would be a security hole big enough to walk three
  1139.           herds of elephants, two marching bands and at least one quarter
  1140.           of the people AT&T laid off through.
  1141.           
  1142.   5.4: CAN I RECORD AUDIO FROM AN APPLET?
  1143.   
  1144.    This is what is known as "a third-party opportunity". In other words
  1145.           not this year and probably not next year either. This would
  1146.           make a neat Java plug-in if anyone cares to write one in C.
  1147.           
  1148.   5.5: HOW DO I MAKE MY APPLETS WORK WELL ON MULTIPLE BROWSERS AND VIRTUAL
  1149.   MACHINES?
  1150.   
  1151.    Java is cross-platform, but that doesn't mean all platforms, browsers,
  1152.           and virtual machines operate identically. However, there are a
  1153.           number of steps a developer can take to ensure that their
  1154.           applet works reasonably well on most browsers.
  1155.           
  1156.          1. Use Java 1.0 only. Use a Java 1.0 compiler and a Java 1.0
  1157.             environment to test in. Do not use Java 1.1.
  1158.             
  1159.          2. From day 1, run your tests in Netscape Navigator 3.0 and
  1160.             earlier. Of browsers that support Java, Navigator's probably
  1161.             the buggiest so if you can get something to work there it's
  1162.             more likely to run elsewhere. In particular, do not develop
  1163.             your applets using the appletviewer. The appletviewer's too
  1164.             reliable and too stable to accurately model real user
  1165.             experience.
  1166.             
  1167.          3. From day 1, include multiple platforms in your tests and
  1168.             development. You may not be able to test on every platform
  1169.             Java supports, but Windows 95 and the Mac are a must. The Mac
  1170.             VMs in Navigator are some of the worst around so it's
  1171.             important to write for them. Windows NT is also a nice test,
  1172.             but I'd stay away from Solaris unless I had lots of time.
  1173.             It's too stable and reliable. However, Linux makes a very
  1174.             nice test since it's a stable OS (which you're not testing
  1175.             against) combined with a buggy VM and a strange GUI (which
  1176.             you are testing against). If you've got multiple people
  1177.             working on the project, have them work on different platforms
  1178.             and report bugs to each other. Better yet have them switch
  1179.             development environments daily so programmers are forced to
  1180.             make sure their code works in all browsers.
  1181.             
  1182.          4. Learn to love layout managers. Provide plenty of extra white
  1183.             space in your user interfaces. Learn to hate absolute
  1184.             positioning. If you must use it, be sure to check font
  1185.             metrics. Don't just eyeball it.
  1186.             
  1187.          5. Avoid filename filters, multiple window interfaces, and other
  1188.             GUI features that don't translate well across platforms.
  1189.             
  1190.    I know this sounds a little perverted. I'm telling you to work with
  1191.           the worst tools rather than the best. But right now Sun's
  1192.           promise of "write once/run anywhere" translates into "write
  1193.           once/debug everywhere". And the fact is, users are far more
  1194.           likely to be using the buggy platforms like Mac/Netscape rather
  1195.           than stable ones like Solaris/appletviewer. Working around a
  1196.           bug in one VM generally doesn't cause problems on other VMs. In
  1197.           fact it will probably make your code more portable to platforms
  1198.           you haven't tested. However, assuming that your development
  1199.           environment is bug-for-bug compatible with users' runtime
  1200.           environments does cause problems. It is much easier to work
  1201.           with multiple platforms from the beginning, rather than
  1202.           developing a great app on Windows or Solaris and then porting
  1203.           it to all the other platforms.
  1204.           
  1205. 6: Language Issues
  1206.  
  1207.   6.1: WHAT DOES IT MEAN THAT A CLASS OR MEMBER IS FINAL?
  1208.   
  1209.    A final class can no longer be subclassed. Mostly this is done for
  1210.           security reasons with basic classes like String and Integer. It
  1211.           also allows the compiler to make some optimizations, and makes
  1212.           thread safety a little easier to achieve.
  1213.           
  1214.           Methods may be declared final as well. This means they may not
  1215.           be overridden in a subclass.
  1216.           
  1217.           Fields can be declared final, too. However, this has a
  1218.           completely different meaning. A final field cannot be changed
  1219.           after it's initialized, and it must include an initializer
  1220.           statement where it's declared. For example,
  1221.           
  1222.           public final double c = 2.998;
  1223.           
  1224.           It's also possible to make a static field final to get the
  1225.           effect of C++'s const statement or some uses of C's #define,
  1226.           e.g.
  1227.           
  1228. public static final double c = 2.998;
  1229.  
  1230.  
  1231.   6.2: WHAT DOES IT MEAN THAT A METHOD OR FIELD IS "STATIC"?
  1232.   
  1233.    Static variables and methods are instantiated only once per class. In
  1234.           other words they are class variables, not instance variables.
  1235.           If you change the value of a static variable in a particular
  1236.           object, the value of that variable changes for all instances of
  1237.           that class.
  1238.           
  1239.           Static methods can be referenced with the name of the class
  1240.           rather than the name of a particular object of the class
  1241.           (though that works too). That's how library methods like
  1242.           System.out.println() work. out is a static field in the
  1243.           java.lang.System class.
  1244.           
  1245.   6.3: WHAT DOES IT MEAN THAT A METHOD OR CLASS IS ABSTRACT?
  1246.   
  1247.    An abstract class cannot be instantiated. Only its subclasses can be
  1248.           instantiated. You indicate that a class is abstract with the
  1249.           abstract keyword like this:
  1250.           
  1251.           public abstract class Container extends Component {
  1252.           
  1253.           Abstract classes may contain abstract methods. A method
  1254.           declared abstract is not actually implemented in the current
  1255.           class. It exists only to be overridden in subclasses. It has no
  1256.           body. For example,
  1257.           
  1258.           public abstract float price();
  1259.           
  1260.           Abstract methods may only be included in abstract classes.
  1261.           However, an abstract class is not required to have any abstract
  1262.           methods, though most of them do.
  1263.           
  1264.           Each subclass of an abstract class must override the abstract
  1265.           methods of its superclasses or itself be declared abstract.
  1266.           
  1267.           For more details, see section 8.1.2.1 of the Java Language
  1268.           Specification.
  1269.           
  1270.   6.4: WHAT'S AN INTERFACE?
  1271.   
  1272.    An interface is an idea taken from Objective C. It describes the
  1273.           public methods that a class implements and their calling
  1274.           conventions without saying anything about how those methods are
  1275.           implemented. It is the responsibility of each class that
  1276.           implements an interface to provide code to handle the cases
  1277.           where the methods of the interface are called.
  1278.           
  1279.           For example suppose you're writing an inventory database. The
  1280.           inventory may include many different items of many different
  1281.           types and classes. However each item in the warehouse needs to
  1282.           be able to tell you its price. Normally you would implement
  1283.           this by having each class extend a common superclass. However
  1284.           that's not always convenient. Instead you can declare an
  1285.           interface called Price with a price() method like this:
  1286.           
  1287. public interface Price {
  1288.  
  1289.   public float price();
  1290.  
  1291. }
  1292.  
  1293.    Any class which implements the Price interface must contain a method
  1294.           with the signature public float price(). The code of the
  1295.           price() method is included separately in each separate class
  1296.           which implements Price, not in the Price interface itself.
  1297.           
  1298.           Different classes in your warehouse can each implement the
  1299.           Price interface like this:
  1300.           
  1301. public class Monopoly extends BoardGame implements Price {
  1302.  
  1303.   // other methods
  1304.  
  1305.   public float price() {
  1306.     return 14.95;
  1307.   }
  1308.  
  1309. }
  1310.  
  1311.    When other code is passed an object, it can test whether the object
  1312.           implements Price with the instanceof operator. For example,
  1313.           
  1314.           if (o instanceof Price) System.out.println("Subtotal is " +
  1315.           o.price());
  1316.           
  1317.           In fact, interfaces can be used to tag objects. The
  1318.           java.rmi.Remote interface declares no methods. Its sole purpose
  1319.           is to indicate that an object is a remote object. In general,
  1320.           sub-interfaces of java.rmi.Remote will declare remote methods,
  1321.           however. For example,
  1322.           
  1323. public interface Hello extends java.rmi.Remote {
  1324.  
  1325.   public String sayHello();
  1326.  
  1327. }
  1328. public class HelloImpl extends UnicastRemoteServer implements Hello {
  1329.  
  1330.   public String sayHello() {
  1331.     return "Hello";
  1332.   }
  1333.  
  1334. }
  1335.  
  1336.    For more information about the java.rmi package, see
  1337.           http://chatsubo.javasoft.com/current/rmi/index.html or
  1338.           Chapter 14 of my book, Java Network Programming, from O'Reilly
  1339.           & Associates.
  1340.           
  1341.   6.5: WHY DOESN'T JAVA INCLUDE INSERT YOUR FAVORITE FEATURE HERE?
  1342.   
  1343.    The Java language has been extensively debated and argued about within
  1344.           Sun. Almost every language construct of existing languages has
  1345.           already been considered for inclusion in Java. While there may
  1346.           still be room for addition, it is very unlikely that your pet
  1347.           feature will be added to the language spec if it isn't already
  1348.           there. In a couple of years parameterized types (i.e.
  1349.           templates) may be added to the language. Otherwise the spec is
  1350.           pretty much frozen except for minor changes and bug fixes.
  1351.           
  1352.           Extensions are planned for the class library though. In
  1353.           particular Sun is working on extensions for 3D, multimedia,
  1354.           telephony, and improved graphics.
  1355.           
  1356.   6.6: IS JAVA CORBA COMPLIANT?
  1357.   
  1358.    Not yet. However work is underway for a Java ORB and IDL.
  1359.           http://splash.javasoft.com/JavaIDL/pages/index.html.
  1360.           
  1361.   6.7: CAN I CAST AN INT TO AN INTEGER? A FLOAT TO A FLOAT?
  1362.   
  1363.    No, you cannot promote a base data type like int or float to an object
  1364.           such as an Integer or a Float. However the proper way to do
  1365.           this isn't very hard. Instead do
  1366.           
  1367. int x = 5;
  1368. myInteger = new Integer(x);
  1369.  
  1370.   6.8: HOW DO I VERSION A CLASS?
  1371.   
  1372.    There is no support for versioning classes in Java 1.0. However in
  1373.           Java 1.1 the serialver tool provides a serialVersionUID for one
  1374.           or more classes you can add to your class as a field. This is
  1375.           used in object serialization.
  1376.           
  1377.   6.9: WHY ISN'T THERE OPERATOR OVERLOADING?
  1378.   
  1379.    Because C++ has proven by example that operator overloading makes code
  1380.           almost impossible to maintain. In fact there very nearly wasn't
  1381.           even method overloading in Java, but it was thought that this
  1382.           was too useful for some very basic methods like print(). Note
  1383.           that some of the classes like DataOutputStream have
  1384.           unoverloaded methods like writeInt() and writeByte().
  1385.           
  1386.   6.10: DOES JAVA HAVE POINTERS?
  1387.   
  1388.    No, no, a thousand times no. Java does not have pointers, no way, no
  1389.           how, the daily email I get from people who think differently
  1390.           not withstanding.
  1391.           
  1392.           Java does have references. A reference is an abstract
  1393.           identifier for an object. It is not a pointer. A reference tags
  1394.           a particular object with a name in the Java virtual machine so
  1395.           that the programmer may refer to it. How exactly the virtual
  1396.           machine implements references at the level of machine code is
  1397.           VM-dependent and completely hidden from the programmer in any
  1398.           case. Most VMs including Sun's use handles, not pointers. A
  1399.           handle is a pointer to a pointer. At the level of machine code
  1400.           in the CPU a reference is an address in memory where the
  1401.           address of the object is stored. This way the objects can be
  1402.           moved around in memory and only the master pointer needs to be
  1403.           updated rather than all references to the object. This is
  1404.           completely hidden from the Java programmer, though. Only the
  1405.           implementer of the virtual machine needs to worry about it.
  1406.           Indeed, this is not the only way references can be implemented.
  1407.           Microsoft's VM actually does use pointers rather than handles.
  1408.           Other schemes are possible.
  1409.           
  1410.   6.11: DOES JAVA PASS METHOD ARGUMENTS BY VALUE OR BY REFERENCE?
  1411.   
  1412.    Java passes all arguments by value, not by reference. However this is
  1413.           one of the few places where the distinction between an object
  1414.           and a reference to an object becomes important. Object and
  1415.           array variables in Java are really references to the object or
  1416.           array. This can make it look like an object is passed by
  1417.           reference if you only modify the fields of the object or array,
  1418.           but do not change the reference itself. For example, consider
  1419.           this program:
  1420.           
  1421. import java.awt.Point;
  1422.  
  1423. class changePoint {
  1424.  
  1425.   public static void main(String args[]) {
  1426.  
  1427.     Point p1 = new Point(0, 0);
  1428.     changePoint(p1);
  1429.     System.out.println(p1);
  1430.  
  1431.   }
  1432.  
  1433.   static void changePoint(Point p) {
  1434.  
  1435.     p.x = 38;
  1436.     p.y = 97;
  1437.  
  1438.   }
  1439.  
  1440. }
  1441.  
  1442.    It prints:
  1443.           
  1444. java.awt.Point[x=38,y=97]
  1445.  
  1446.    Therefore the point has been changed. However the reference, which is
  1447.           what was really passed, has not been changed. To see that
  1448.           consider the following program.
  1449.           
  1450. import java.awt.Point;
  1451.  
  1452.  
  1453. class dontChangePoint {
  1454.  
  1455.   public static void main(String args[]) {
  1456.  
  1457.     Point p1 = new Point(0, 0);
  1458.     dontChangePoint(p1);
  1459.     System.out.println(p1);
  1460.  
  1461.   }
  1462.  
  1463.   static void dontChangePoint(Point p) {
  1464.  
  1465.     p = new Point(38, 97);
  1466.  
  1467.   }
  1468.  
  1469. }
  1470.  
  1471.    It prints:
  1472.           
  1473.  
  1474. java.awt.Point[x=0,y=0]
  1475.  
  1476.    What happened in this example was that a copy of the reference p1 was
  1477.           passed to the dontChangePoint() method. A new Point object was
  1478.           then assigned to that copy. However this did not change the old
  1479.           reference in the main method. In the previous example the
  1480.           reference p in the changePoint() method and p1 in the main()
  1481.           method both referred to the same object. In this example p and
  1482.           p1 refer to different objects after the new Point is assigned
  1483.           to p.
  1484.           
  1485.   6.12: ARE THERE PARAMETERIZED TYPES (TEMPLATES)?
  1486.   
  1487.    Not in Java 1.0 or 1.1. However this is being seriously considered for
  1488.           future versions.
  1489.           
  1490.   6.13: HOW DOES GARBAGE COLLECTION WORK?
  1491.   
  1492.    Current implementations of Java use a mark and sweep garbage
  1493.           collector. Reference counting is not used. Thus circular linked
  1494.           lists do not lead to memory leaks. It is theoretically possible
  1495.           that future versions of Java will use some other garbage
  1496.           collection algorithm.
  1497.           
  1498.   6.14: PERFORM AND BECOME
  1499.   
  1500.    Sorry Smalltalkers. There's no equivalent for PERFORM or BECOME in
  1501.           Java 1.0. These would probably open security holes. There are
  1502.           workarounds for some things you might want to do using
  1503.           interfaces.
  1504.           
  1505.           In Java 1.1 the Core Reflection API and the java.lang.reflect
  1506.           package provides most of the functionality you need. However
  1507.           this API is partially unavailable to applets due to security
  1508.           issues.
  1509.           
  1510. 7: java.awt
  1511.  
  1512.   7.1: WHAT DOES AWT STAND FOR?
  1513.   
  1514.    So far I've heard it claimed that AWT stands for:
  1515.           
  1516.           + Abstract Window Toolkit
  1517.           + Advanced Window Toolkit
  1518.           + Another Window Toolkit
  1519.           + Applet Window Toolkit
  1520.           + Awkward Window Toolkit
  1521.           + Annoying Window Toolkit
  1522.             
  1523.    I do not know which if any of these are correct, but Abstract Window
  1524.           Toolkit seems to be the most popular.
  1525.           
  1526.   7.2: WHAT ARE PEER "CLASSES"?
  1527.   
  1528.    Peer classes exist mainly for the convenience of the people who wrote
  1529.           the Java environment. They help in translating between the AWT
  1530.           user interface and the native (Windows, OpenWindows, Mac etc.)
  1531.           interfaces. Unless you're porting Java to a new platform you
  1532.           shouldn't have to use them.
  1533.           
  1534.   7.3: CAN YOU EXPLAIN HOW EVENTS ARE PASSED?
  1535.   
  1536.    The following applies to Java 1.0 only. The event mechanism has
  1537.           changed completely in Java 1.1, though the following is
  1538.           retained for backwards compatibility.
  1539.           
  1540.           Components are subclasses of java.awt.Component. Examples of
  1541.           components include buttons, scrollbars, text fields, frames,
  1542.           windows, dialogs, panels, canvases, and checkboxes. One
  1543.           subclass of java.awt.Component is java.awt.Container. A
  1544.           container is a component which can hold other components.
  1545.           Examples of containers include Frames, Windows, Dialogs, Panels
  1546.           and Applets. An applet is a subclass of Panel. Panel is a
  1547.           subclass of Container. Container is a subclass of Component.
  1548.           Therefore an applet is both a container and a component.
  1549.           
  1550.           When the user clicks the mouse, types on the keyboard, drags
  1551.           and drops, or does any of a few other things, the operating
  1552.           system produces an event. This event is passed to Java, and the
  1553.           Java runtime tries to figure out which component the event was
  1554.           intended for.
  1555.           
  1556.           The Java runtime then passes that event to the
  1557.           handleEvent(Event e) method of some Component. The Component's
  1558.           handleEvent() method contains a big if-else statement to look
  1559.           at the type of event and respond appropriately. What the
  1560.           handleEvent() method does depends on the type of component.
  1561.           Generally some events are ignored and other events are passed
  1562.           to methods that know how to respond to those events. For
  1563.           instance a MOUSE_DOWN event is passed to mouseDown(). The table
  1564.           below shows the events the default handleEvent() can deal with.
  1565.           When one of these events occurs, handleEvent() passes it and
  1566.           various other information to the specified method.
  1567.           
  1568.  
  1569. Event                      Method Called
  1570. --------------------------------------------------------
  1571. Event.MOUSE_ENTER:         mouseEnter(evt, evt.x, evt.y)
  1572. Event.MOUSE_EXIT:          mouseExit(evt, evt.x, evt.y)
  1573. Event.MOUSE_MOVE:          mouseMove(evt, evt.x, evt.y)
  1574. Event.MOUSE_DOWN:          mouseDown(evt, evt.x, evt.y)
  1575. Event.MOUSE_DRAG:          mouseDrag(evt, evt.x, evt.y)
  1576. Event.MOUSE_UP:            mouseUp(evt, evt.x, evt.y)
  1577. Event.KEY_PRESS:           keyDown(evt, evt.key)
  1578. Event.KEY_ACTION:          keyDown(evt, evt.key)
  1579. Event.KEY_RELEASE:         keyUp(evt, evt.key)
  1580. Event.KEY_ACTION_RELEASE:  keyUp(evt, evt.key)
  1581. Event.ACTION_EVENT:        action(evt, evt.arg)
  1582. Event.GOT_FOCUS:           gotFocus(evt, evt.arg)
  1583. Event.LOST_FOCUS:          lostFocus(evt, evt.arg)
  1584.  
  1585.    By default each of these methods does nothing. Furthermore, by default
  1586.           all other events do nothing. If you want to do something when
  1587.           one of the above events occurs in your component, subclass the
  1588.           component and override the appropriate method. For example, to
  1589.           create a Canvas that prints the message "Don't Tread on Me!"
  1590.           every time the user clicks on it, use the following subclass of
  1591.           Canvas:
  1592.           
  1593. public class noTread extends Canvas {
  1594.  
  1595.   public boolean mouseDown(Event e, int x, int y) {
  1596.     System.out.println("Don't Tread on Me!");
  1597.     return true;
  1598.   }
  1599.  
  1600. }
  1601.  
  1602.    Button, Choice, TextField, and Checkbox are special because of how
  1603.           they're implemented as native widgets. They do not see
  1604.           MOUSE_DOWN, MOUSE_UP, KEY_PRESS, and other such events. Rather
  1605.           they receive one event and one event only: Event.ACTION_EVENT.
  1606.           When a Button is pressed, the user hits return in a TextField,
  1607.           the user double clicks on a List item, clicks a Checkbox, or
  1608.           selects from a Choice, an ACTION_EVENT is generated. If you
  1609.           haven't overridden handleEvent(), this is passed to the
  1610.           action() method of the component's container. These four
  1611.           components are the only things which generate ACTION_EVENTs. No
  1612.           other component will generate an ACTION_EVENT. (Menu items,
  1613.           which are not components but are implemented as native peers,
  1614.           also generate action events.)
  1615.           
  1616.           Each event handler method, including handleEvent(), returns
  1617.           true if the event was completely handled and false if it was
  1618.           not. If false is returned, then the event is passed to the
  1619.           component's container to see if the container wants to process
  1620.           the event.
  1621.           
  1622.           If you want to respond to a different set of events, you must
  1623.           override handleEvent(). You can either completely replace it or
  1624.           just add the extra events you want to handle and then return
  1625.           super.handleEvent() for other types of events. For example to
  1626.           print all the events as they happen in your applet you might
  1627.           use this handleEvent() method:
  1628.           
  1629. public boolean handleEvent(Event e, int x, int y) {
  1630.   System.out.println(e);
  1631.   return super.handleEvent(e, x, y);
  1632. }
  1633.  
  1634.    mouseDown(), mouseUp(), keyDown(), and all the other event methods
  1635.           would still be called by the superclass. If you don't handle an
  1636.           event in the handleEvent() method, return super.handleEvent(e)
  1637.           to give your superclass an opportunity to process the event. In
  1638.           this case, we've handled the event but not completely so we
  1639.           still let the superclass process it by returning
  1640.           super.handleEvent(e, int x, int y).
  1641.           
  1642.           The return value of handleEvent() is important. If
  1643.           handleEvent() returns true, that means the event has been fully
  1644.           digested and no further processing is needed. On the other hand
  1645.           if handleEvent() returns false, then the event is passed to the
  1646.           component's container to be handled.
  1647.           
  1648.           Note that this all works for any component at all. You'll most
  1649.           commonly override these methods in a subclass of Applet or
  1650.           perhaps Frame. However the same methods and techniques apply to
  1651.           all subclasses of Component.
  1652.           
  1653.           The API documentation confuses the issue because of the
  1654.           ambigious use of the word parent. In object-oriented circles
  1655.           the word parent usually refers to the superclass. However in
  1656.           the context of the AWT, the word parent refers to the container
  1657.           that contains a component. Thus in the statement:
  1658.           
  1659.      return true if the event has been handled and no further action is
  1660.      necessary; false if the event is to be given to the component's
  1661.      parent
  1662.      
  1663.    the word parent means the component's container, not its superclass.
  1664.           
  1665.           You must distinguish between the container/component hierarchy
  1666.           and the inheritance hierarchy. By default, the way an event
  1667.           travels has nothing to do with the inheritance hieararchy. If
  1668.           you override an event handling method, then events passed to
  1669.           that method will not be passed to a component's superclass
  1670.           unless you specifically ask them to be. However, in most cases
  1671.           your handleEvent() method will return super.handleEvent() to
  1672.           give the superclass a crack at handling the event rather than
  1673.           simply returning false.
  1674.           
  1675.           To sum up, when you write a subclass of Component, you can
  1676.           either respond to specific events by overriding the methods
  1677.           that correspond to those events, such as mouseDown(); or you
  1678.           can respond to all events by overriding handleEvent(). Each of
  1679.           your event handling methods must return a boolean. Return true
  1680.           when an event has been completely processed, and return false
  1681.           when you want the component's container to try to handle the
  1682.           event. When overriding handleEvent(), you also have an option
  1683.           to return super.handleEvent() to ask the superclass to handle
  1684.           the event and decide whether or not to pass it along to the
  1685.           component's container.
  1686.           
  1687.   7.4: CLIPPING
  1688.   
  1689.    java.awt.Graphics.clipRect(int, int, int, int) and related methods are
  1690.           hopelessly flawed, at least as of 1.0. Ignore them completely.
  1691.           
  1692.           Instead if you need to do clipping, create separate offscreen
  1693.           Images for each clipping region. Each Image should be the
  1694.           size of the clipping region you desire. Draw into those
  1695.           offscreen images, and then copy them onto the appropriate
  1696.           section of the of your applet window using
  1697.           java.awt.Graphics.drawImage(). Some coordinate conversion
  1698.           will almost certainly be necessary.
  1699.           
  1700.           If the background image isn't a simple color then you'll first
  1701.           need to copy the appropriate part of that image to your
  1702.           offscreen clipping Image. You can do this by drawing your
  1703.           background Image into your offscreen region with
  1704.           Graphics.drawImage() and a suitable shifting of coordinates.
  1705.           
  1706.           This all works for rectangular regions only since all Images
  1707.           are rectangular. More complicated geometries can be faked if
  1708.           all but one section contains only simple colors.
  1709.           
  1710.   7.5: HOW DO I CHANGE THE THICKNESS OF THE LINE?
  1711.   
  1712.    Java 1.1 and earlier only support 1 pixel wide lines. There's no easy
  1713.           way around this. You can, however, draw multiple, parallel
  1714.           lines offset from each other by one pixel:
  1715.           
  1716.   public void paint(Graphics g) {
  1717.  
  1718.     int x1=5;
  1719.     int x2=278;
  1720.     int y1=8;
  1721.     int y2=93;
  1722.  
  1723.  
  1724.     // Draw a ten pixel thick line
  1725.     for (int i = -5; i < 5; i++) {
  1726.       g.drawLine(x1+i,y1+i,x2+i,y2+i);
  1727.     }
  1728.  
  1729.   }
  1730.  
  1731.    This isn't perfect. The ends of the line are excessively tapered. You
  1732.           really need to take the slope of the line into account when
  1733.           incrementing x and y, but this should give you the idea. If
  1734.           you're doing a lot of this, you can write a class or method to
  1735.           do it for you.
  1736.           
  1737.           There are other hacks you can use. For example, a thick line is
  1738.           essentially a filled rectangle. Therefore you can calculate the
  1739.           endpoints of the rectangle and use fillPolygon() to draw it.
  1740.           
  1741.           The real solution is going to have to wait for a more complete
  1742.           graphics API for Java, possibly in Java 1.2.
  1743.           
  1744.           
  1745.           
  1746.   7.6: WHAT FONTS DOES JAVA SUPPORT?
  1747.   
  1748.    Java 1.0 implementations are guaranteed to have the fonts Helvetica,
  1749.           Courier, TimesRoman, and Symbol or some reasonable facsimile
  1750.           thereof.
  1751.           
  1752.           These names are deprecated in Java 1.1. In Java 1.1 you should
  1753.           use SansSerif, Serif, and Mono instead which will be mapped to
  1754.           an appropriate font like Helvetica, Times, or Courier.
  1755.           
  1756.           Whether fonts installed on the client are available to Java is
  1757.           implementation depenedent. You can get a String array of the
  1758.           names of the available fonts by calling the getFontList()
  1759.           method from java.awt.Toolkit. For example,
  1760.           
  1761.           String[] fonts = Toolkit.getDefaultToolkit().getFontList()
  1762.           
  1763. 8: java.io
  1764.  
  1765.   8.1:HOW DO I READ DATA FROM A FILE?
  1766.   
  1767.    There are a number of ways to read data from a file. If you're reading
  1768.           a file as raw binary data, you open a file using a
  1769.           FileInputStream(String) constructor and use one of the various
  1770.           read() methods to read the data into an array of bytes. For
  1771.           example the following program reads raw data from a file
  1772.           specified on the command line. It then writes the same data to
  1773.           the standard output.
  1774.           
  1775. import java.io.*;
  1776.  
  1777. class ReadRawData {
  1778.  
  1779.   public static void main (String args[]) {
  1780.  
  1781.     boolean done = false;
  1782.     byte b[] = new byte[1024];
  1783.     int num_bytes = 0;
  1784.  
  1785.     FileInputStream fin = null;
  1786.     try {
  1787.       fin = new FileInputStream(args[0]);
  1788.     }
  1789.     catch(ArrayIndexOutOfBoundsException e) {
  1790.       System.out.println("You have to give me the name of a file to open.");
  1791.       System.exit(0);
  1792.     }
  1793.     catch (FileNotFoundException e) {
  1794.       System.out.println("Could not open input file " + args[0]);
  1795.       System.exit(0);
  1796.     }
  1797.     catch(IOException e) {
  1798.       System.out.println("Error while opening input file" + args[0]);
  1799.       System.exit(0);
  1800.     }
  1801.     catch (Exception e) {
  1802.       System.out.println("Unexpected exception: " + e);
  1803.       System.exit(0);
  1804.     }
  1805.  
  1806.     try {
  1807.       num_bytes = fin.read(b);
  1808.     }
  1809.     catch(IOException e) {
  1810.       System.out.println("Finished Reading: " + e);
  1811.       done = true;
  1812.     }
  1813.     catch (Exception e) {
  1814.       System.out.println("Unexpected exception: " + e);
  1815.       System.exit(0);
  1816.     }
  1817.  
  1818.     while(!done) {
  1819.       System.out.write(b, 0, num_bytes);
  1820.       try {
  1821.         num_bytes = fin.read(b);
  1822.       }
  1823.       catch(IOException e) {
  1824.         System.out.println("Finished Reading: " + e);
  1825.         done = true;
  1826.       }
  1827.       catch (Exception e) {
  1828.         System.out.println("Unexpected exception: " + e);
  1829.         System.exit(0);
  1830.       }
  1831.       if (num_bytes == -1) done = true;
  1832.    }  // end while
  1833.  
  1834.  }  // end main
  1835.  
  1836. } // end ReadRawData
  1837.  
  1838.    On the other hand if you're reading a text file in Java 1.0 you'll
  1839.           probably want to use a DataInputStream which gives you a
  1840.           readLine() method that returns successive lines of the file as
  1841.           Java Strings. You can then process each String as you see fit.
  1842.           
  1843. // Implement the Unix cat utility in java
  1844.  
  1845. import java.io.*;
  1846.  
  1847. class cat  {
  1848.  
  1849.   public static void main (String args[]) {
  1850.  
  1851.     String thisLine;
  1852.  
  1853.    //Loop across the arguments
  1854.    for (int i=0; i < args.length; i++) {
  1855.  
  1856.      //Open the file for reading
  1857.      try {
  1858.        FileInputStream fin =  new FileInputStream(args[i]);
  1859.  
  1860.        try {
  1861.          DataInputStream myInput = new DataInputStream(fin);
  1862.  
  1863.          try {
  1864.            while ((thisLine = myInput.readLine()) != null) {  // while loop beg
  1865. ins here
  1866.              System.out.println(thisLine);
  1867.            } // while loop ends here
  1868.          }
  1869.          catch (Exception e) {
  1870.            System.out.println("Error: " + e);
  1871.          }
  1872.       } // end try
  1873.       catch (Exception e) {
  1874.         System.out.println("Error: " + e);
  1875.       }
  1876.  
  1877.     } // end try
  1878.     catch (Exception e) {
  1879.       System.out.println("failed to open file " + args[i]);
  1880.       System.out.println("Error: " + e);
  1881.     }
  1882.   } // for ends here
  1883.  
  1884. } // main ends here
  1885.  
  1886. }
  1887.  
  1888.    This code emulates the Unix "cat" command. Given a series of filenames
  1889.           on the command line it concatenates the files onto the standard
  1890.           output.
  1891.           
  1892.           In Java 1.1 DataInputStream.readLine() is deprecated. You
  1893.           should use a BufferedReader instead as in this class:
  1894.           
  1895. // Implement the Unix cat utility in java
  1896.  
  1897. import java.io.*;
  1898.  
  1899. class cat {
  1900.  
  1901.   public static void main (String args[]) {
  1902.  
  1903.     String thisLine;
  1904.  
  1905.    //Loop across the arguments
  1906.    for (int i=0; i < args.length; i++) {
  1907.  
  1908.      //Open the file for reading
  1909.      try {
  1910.        FileReader fr =  new FileReader(args[i]);
  1911.        BufferedReader myInput = new BufferedReader(fr);
  1912.  
  1913.        while ((thisLine = myInput.readLine()) != null) {  // while loop begins
  1914. here
  1915.          System.out.println(thisLine);
  1916.        } // while loop ends here
  1917.  
  1918.      } // end try
  1919.      catch (IOException e) {
  1920.        System.out.println("Error: " + e);
  1921.      }
  1922.  
  1923.   } // for ends here
  1924.  
  1925. } // main ends here
  1926.  
  1927. }
  1928.  
  1929.   8.2: HOW DO I WRITE DATA TO A FILE?
  1930.   
  1931.    You should only assume you'll be able to write to a file from an
  1932.           application. Although it may be possible to write data into a
  1933.           file from an applet if the browser viewing the applet is
  1934.           HotJava, this ability will generally be disabled. From within
  1935.           Netscape there is no way for an applet to write to a file on
  1936.           the local hard drive.
  1937.           
  1938.           Within an application, however, file access is
  1939.           straight-forward. There are several ways but here is a simple
  1940.           example using formatted output streams:
  1941.           
  1942. import java.io.*;
  1943.  
  1944. class PrintToAFile  {
  1945.  
  1946.   public static void main (String args[]) {
  1947.  
  1948.     //First open the file you want to write into
  1949.     try {
  1950.       FileOutputStream fout =  new FileOutputStream("test.out");
  1951.  
  1952.       // now convert the FileOutputStream into a PrintStream
  1953.  
  1954.       PrintStream myOutput = new PrintStream(fout);
  1955.  
  1956.       // Now you're able to use println statements just as if you were using Sy
  1957. stem.out.println
  1958.       // to write to the terminal
  1959.  
  1960.       myOutput.println("Hello There!");
  1961.       myOutput.println(1 + " + " + 1 + " = " + (1+1));
  1962.     }
  1963.     catch (IOException e) {
  1964.       System.out.println("Error opening file: " + e);
  1965.       System.exit(1);
  1966.     }
  1967.  
  1968.   } // main ends here
  1969.  
  1970. }
  1971.  
  1972.    There are a number of other things to note about writing data to a
  1973.           file. This program creates or opens a file called "test.out" in
  1974.           the same directory as the running program. However you could
  1975.           pass it a full pathname to a file in a different directory
  1976.           instead.
  1977.           
  1978.           You should also learn about the DataOutputStream class and the
  1979.           write() method when you get a chance. DataOutputStreams and
  1980.           DataInputStreams are used for moving data between Java programs
  1981.           in a portable way. The various incarnations of the write()
  1982.           method are used for writing and reading arbitrary byte streams.
  1983.           What I've demonstrated here is more suitable for human
  1984.           consumption.
  1985.           
  1986.           In Java 1.1 you should probably use a PrintWriter instead of a
  1987.           PrintStream.
  1988.           
  1989.   8.3: HOW DO I APPEND DATA TO A FILE?
  1990.   
  1991.    In Java 1.1 you can just pass true as the second argument to this
  1992.           FileOutputStream constructor to indicate that you want to
  1993.           append data to the file:
  1994.           
  1995. public FileOutputStream(String name, boolean append)
  1996.  throws IOException
  1997.  
  1998.    In Java 1.0, however, you must use the java.io.RandomAccessFile class
  1999.           that lets you read and write bytes from arbitrary locations in
  2000.           a file. This class implements DataInput and DataOutput so you
  2001.           have all the methods of DataInputStream and DataOutputStream
  2002.           available to you.
  2003.           
  2004.            To create a new random access file pass the name of the file
  2005.           and the mode to the constructor. The mode is either "r"
  2006.           (read-only) or "rw" (read and write). The length() method
  2007.           returns a long that tells you how many bytes there are in a
  2008.           file and the seek(long p) method lets you position the file
  2009.           pointer at a particular point in the file. Thus to start
  2010.           writing at the end of a RandomAccessFile raf, you first
  2011.           raf.seek(raf.length()). The following example demonstrates by
  2012.           appending the string "Kilroy was here!" to every file specified
  2013.           on the command line.
  2014.           
  2015. import java.io.*;
  2016.  
  2017. class AppendToAFile  {
  2018.  
  2019.   public static void main (String args[]) {
  2020.  
  2021.     for (int i = 0; i < args.length; i++) {
  2022.       //First open the file you want to append to
  2023.  
  2024.       try {
  2025.         RandomAccessFile raf =  new RandomAccessFile(args[i], "rw");
  2026.         // Position yourself at the end of the file
  2027.         raf.seek(raf.length());
  2028.  
  2029.        // Write the String into the file. Note that you must
  2030.        // explicitly handle line breaks.
  2031.        raf.writeBytes("\nKilroy was here!\n");
  2032.  
  2033.       }
  2034.       catch (IOException e) {
  2035.         System.out.println("Error opening file: " + e);
  2036.       }
  2037.  
  2038.     }
  2039.  
  2040.   }
  2041.  
  2042. }
  2043.  
  2044.   8.4: HOW DO I FORMAT NUMBERS LIKE C'S PRINTF()?
  2045.   
  2046.    Java does not have any built in equivalent to C's
  2047.           printf/sprintf/fprintf family of functions that specify the
  2048.           width and precision of numbers converted into strings. Since
  2049.           Java does not support variable length argument lists, it's not
  2050.           possible to write exact equivalents for these functions.
  2051.           Instead the approach that must be taken is to convert one
  2052.           number at a time into a string according to a format
  2053.           specification, then write the resulting string onto the
  2054.           appropriate output stream. This is a more flexible solution,
  2055.           but it's far from obvious.
  2056.           
  2057.           In Java 1.1, the java.text package contains classes that format
  2058.           numbers according to particular needs. In particular it's worth
  2059.           getting to know the java.text.NumberFormat and
  2060.           java.text.DecimalFormat classes, though these can't handle
  2061.           exponential notation. I've begun work on my own formatting
  2062.           class that does handle exponential and other notations
  2063.           available through printf(). It can be found at
  2064.           http://sunsite.unc.edu/javafaq/formatter/. Gary Cornell and
  2065.           Cay Horstmann's popular book Core Java also includes such a
  2066.           class. You can probably find more at Gamelan.
  2067.           
  2068. 9: java.net
  2069.  
  2070.    Network programming in Java is covered in much more detail in my book,
  2071.           Java Network Programming from O'Reilly & Associates. Most of
  2072.           what is new and exciting about Java centers around the
  2073.           potential for new kinds of dynamic, networked applications; and
  2074.           Java Network Programming shows you how to write them. Topics
  2075.           covered include sockets, URLs, InetAddresses, UDP, TCP/IP,
  2076.           multicasting, applets, servlets, RMI, and more.
  2077.           
  2078.           Manning Publications has also recently published a book titled
  2079.           Java Network Programming. It's not a bad book, and is
  2080.           surprisingly orthogonal to mine. About 2/3 of that book is
  2081.           streams and encryption which I only touch on. My book covers
  2082.           servlets, applets, RMI, multicast sockets, and Java 1.1 which
  2083.           that book doesn't discuss. The matching titles appear to be
  2084.           just unlucky choices. Both publishers went with the most
  2085.           obvious title they could think of. However the cover of the
  2086.           Manning book has a big fish, and looks suspiciously like an
  2087.           O'Reilly book. Don't be fooled. The real O'Reilly book has a
  2088.           gyroscope on the cover.
  2089.           
  2090.           You can buy Java Network Programming at any bookstore that
  2091.           stocks computer books, or you can order it from amazon.com or
  2092.           Computer Literacy.
  2093.           
  2094.           
  2095.           
  2096.   9.1: HOW DO I CONVERT A NUMERIC IP ADDRESS LIKE 199.1.32.90 INTO A HOSTNAME
  2097.   LIKE STAR.BLACKSTAR.COM?
  2098.   
  2099.    Unfortunately due to an unintended side effect (i.e. a bug) in Java's
  2100.           caching of IP addresses and hostnames, Java 1.0 can't convert
  2101.           numeric IP addresses into hostnames. However this is
  2102.           straightforward in Java 1.1. For example,
  2103.           
  2104.           String hostname =
  2105.           InetAddress.getByName("199.1.32.90").getHostName()
  2106.           
  2107.   9.2: HOW CAN A JAVA PROGRAM TALK TO A CGI PROGRAM?
  2108.   
  2109.    Web browsers display forms, read user input, encode that input into a
  2110.           standard format called a "query string", and send that data to
  2111.           CGI programs that live on the web server. When you write an
  2112.           applet that talks to a CGI program, you have to do all this
  2113.           yourself.
  2114.           
  2115.           The first thing to know is that there are two ways a CGI
  2116.           program can accept data from a web browser, GET and POST. CGIs
  2117.           that use GET take their arguments from the URL. Programs that
  2118.           use POST read their arguments from standard input.
  2119.           
  2120.           The second thing to know is that when you submit data to a form
  2121.           through a web browser, the web browser encodes the data for
  2122.           you. In an applet, however, you need to encode the data
  2123.           yourself. The data is encoded like this: Each form entry is a
  2124.           name-value pair. Names and values are separated from each other
  2125.           by equals signs (=). Pairs are separated from each other by
  2126.           ampersands (&). For example, consider this form:
  2127.           
  2128. <Form method=GET action="http://sunsite.unc.edu/javafaq/cgi-bin/getform.pl">
  2129. Email: <Input NAME="email" size=40>
  2130. Name: <Input NAME="realname" size=40>
  2131. <Input TYPE="submit" VALUE="Subscribe">
  2132. </Form>
  2133.  
  2134.    You see that this uses the GET method to communicate with a cgi-bin
  2135.           program at http://sunsite.unc.edu/javafaq/cgi-bin/getform.pl.
  2136.           It sends two fields to the CGI program, email and realname.
  2137.           Let's say you want to send the string "elharo@sunsite.unc.edu"
  2138.           for the email address, and the string "Elliotte Harold" for the
  2139.           real name. Then the query string would look like this:
  2140.           
  2141.           String qs =
  2142.           "email=elharo%40sunsite.unc.edu&realname=Elliotte%20Harold";
  2143.           
  2144.           The spaces in "Elliotte Harold" and the @ in
  2145.           "elharo@sunsite.unc.edu" have been converted into percent
  2146.           escapes. All non-alphanumeric characters in the values must be
  2147.           replaced with a % followed by their ASCII value. Thus a space
  2148.           becomes %20 and the @ becomes %40.
  2149.           
  2150.           To send this data to the server, append a question mark (?) and
  2151.           the query string to the URL of the CGI program, and request
  2152.           that URL from the server. Thus the URL you want is:
  2153.           
  2154. http://sunsite.unc.edu/javafaq/cgi-bin/getform.pl?email=elharo%40sunsite.unc.ed
  2155. u;realname=Elliotte%20Harold";
  2156.  
  2157.    In Java terms this requires constructing a URL object from this
  2158.           string, and opening that URL's InputStream to read the
  2159.           response. The following code fragment demonstrates:
  2160.           
  2161. try {
  2162.   String thisLine;
  2163.   String qs = ""email=elharo%40sunsite.unc.edu&realname=Elliotte%20Harold";
  2164.   URL u = new URL("http://sunsite.unc.edu/javafaq/cgi-bin/getform.pl?" + qs);
  2165.   DataInputStream theHTML = new DataInputStream(u.openStream());
  2166.   while ((thisLine = theHTML.readLine()) != null) {
  2167.     System.out.println(thisLine);
  2168.   }
  2169. }
  2170. catch (Exception e) {
  2171.   System.err.println(e);
  2172. }
  2173.  
  2174.    Communicating with CGI programs that use POST is somewhat more
  2175.           complex, and it doesn't work very well in Java 1.0.2. It may be
  2176.           improved in Java 1.1. When POSTing to a CGI, you encode the
  2177.           query string exactly as you do for GET requests. However
  2178.           instead of merely requesting a URL's InputStream, you open a
  2179.           URLConnection to the CGI program.
  2180.           
  2181.           Do not append the query string to the URL as you did with GET.
  2182.           Instead set the URLConnection's doOutput and doInput fields to
  2183.           true and set AllowUserInteraction to false. Chain the
  2184.           URLConnection's OutputStream to a DataOutputStream and use the
  2185.           DataOutputStream's writeBytes() method to send the query string
  2186.           to the server.
  2187.           
  2188.           If you want to read the response, then chain the
  2189.           URLConnection's InputStream to a DataInputStream, and use the
  2190.           DataInputStream's readLine() method to read the response in a
  2191.           while loop. The following code fragment demonstrates:
  2192.           
  2193. String query = "email=elharo%40sunsite.unc.edu;realname=Elliotte%20Harold";
  2194.  
  2195. try {
  2196.  
  2197.   // open the connection and prepare it to POST
  2198.   URL u = new URL("http://sunsite.unc.edu/javafaq/cgi-bin/postform.pl");
  2199.   URLConnection uc = u.openConnection();
  2200.   uc.setDoOutput(true);
  2201.   uc.setDoInput(true);
  2202.   uc.setAllowUserInteraction(false);
  2203.   DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
  2204.  
  2205.   // Send the data
  2206.   dos.writeBytes(query);
  2207.   dos.close();
  2208.  
  2209.  
  2210.   // Read the response
  2211.   DataInputStream dis = new DataInputStream(uc.getInputStream());
  2212.   String nextline;
  2213.   while((nextline = dis.readLine()) != null) {
  2214.    System.out.println(nextline);
  2215.   }
  2216.   dis.close();
  2217.  
  2218. }
  2219. catch (Exception e) {
  2220.   System.err.println(e);
  2221. }
  2222.  
  2223.    As you see, posting forms is considerably more complex than using the
  2224.           GET method. However on some platforms, GET has an annoying
  2225.           habit of failing once the query string grows past 200
  2226.           characters. The exact point where GET fails varies depending on
  2227.           the operating system and the web server.
  2228.           
  2229.   9.3: HOW CAN AN APPLET SEND EMAIL?
  2230.   
  2231.    The simplest way to answer this question is to tell you to write a CGI
  2232.           program which sends email, and then refer you to the previous
  2233.           question to learn how to communicate with the CGI program.
  2234.           There really isn't any other reliable, cross-platform way to
  2235.           send email. The problem is that email programs are platform
  2236.           dependent.
  2237.           
  2238.           The Simple Mail Transport Protocol is an Internet standard that
  2239.           you may be able to use some of the time. The basic idea is to
  2240.           open a socket to the SMTP port, 25, on the web server, and send
  2241.           your email through the server. However not all web servers,
  2242.           especially those based on Macs or Windows NT, run SMTP servers,
  2243.           and an applet can't open sockets to other hosts. Even if you do
  2244.           have SMTP software running on your web server, the applet may
  2245.           be behind a firewall that disallows outgoing connections to
  2246.           port 25 on hosts outside the firewall.
  2247.           
  2248.   9.4: HOW CAN I USE ICMP IN JAVA?
  2249.   
  2250.    Java does not support ICMP, the Internet Control Message Protocol, at
  2251.           this time; nor does it allow you to send raw IP packets. You
  2252.           must use TCP or UDP. Therefore protocols that rely on ICMP like
  2253.           ping and traceroute cannot yet be implemented in Java.
  2254.           
  2255.   9.5: HOW DO I MAKE JAVA WORK WITH A PROXY SERVER?
  2256.   
  2257.    The socksProxyHost, socksProxyPort, http.proxyHost, and http.proxyPort
  2258.           system properties define the proxy server used to support SOCKS
  2259.           v4 and HTTP proxy functionality:
  2260.           
  2261. socksProxyHost // for socks v4
  2262. socksProxyPort
  2263. http.proxyHost // standard HTTP proxy
  2264. http.proxyPort
  2265.  
  2266.    This is documented in the HotJava documentation, but applies to the
  2267.           JDK too. You can set system properties from the command line
  2268.           like this
  2269.           
  2270. java -DsocksProxyHost=utopia.poly.edu -DsocksProxyPort=9087  MyClass
  2271.  
  2272.    Of course you have to change it to use your proxy host and port.
  2273.           
  2274.           These can also be set by any other convenient means to set
  2275.           system properties, such as including them in the
  2276.           appletviewer.properties file like this:
  2277.           
  2278. # caching
  2279. proxySet=true
  2280. proxyHost=proxy.mysite.com
  2281. proxyPort=8080
  2282.  
  2283. # ftp
  2284. ftpProxySet=true
  2285. ftpProxyHost=ftpprxy.mysite.com
  2286. ftpProxyPort=7070
  2287.  
  2288. 10: java.util
  2289.  
  2290.   10.1: HOW RANDOM IS RANDOM()?
  2291.   
  2292.    It's good enough for games. I wouldn't use it for cryptography.
  2293.           
  2294.           Unlike most random functions in other libraries the
  2295.           Math.random() method seeds itself with the current time in
  2296.           milliseconds. Thus you do not need to seed it explicitly at the
  2297.           start of your program. If you require a non-random Random() for
  2298.           test purposes or you need more randomness than the current time
  2299.           in milliseconds can provide, then you can use
  2300.           java.util.Random() which has a constructor that lets you
  2301.           specify a seed.
  2302.           
  2303.   10.2: HOW DO I GENERATE A RANDOM INTEGER BETWEEN A AND B?
  2304.   
  2305.    Generate a random double between 0.0 and 1.0, multiply by the number
  2306.           of int values you want to choose from, add the smallest int
  2307.           value you want, round it down to the nearest integer using
  2308.           Math.floor(), and cast the result to an int. For example, the
  2309.           following class simulates a six-sided die by producing random,
  2310.           uniformly distributed ints between 1 and 6.
  2311.           
  2312. public class Die {
  2313.  
  2314.   Random generator = new Random();
  2315.  
  2316.   public static int roll() {
  2317.  
  2318.     // get a rcandom number between 0 and 1
  2319.     double r = generator.nextDouble();
  2320.  
  2321.     // multiply by 6 so it's now between 0 and 6
  2322.     r *= 6.0;
  2323.  
  2324.     // add 1
  2325.     r += 1.0;
  2326.  
  2327.     //truncate it to an int
  2328.     r = Math.floor(r);
  2329.  
  2330.     // handle one special if unlikely case
  2331.     if (r == 7.0) r = 6.0;
  2332.  
  2333.     // convert to an int and return
  2334.     return (int) r;
  2335.  
  2336.   }
  2337.  
  2338. }
  2339.  
  2340. 11: Common Errors and Problems
  2341.  
  2342.   11.1: HOW CAN I AVOID FLICKER IN AN APPLET?
  2343.   
  2344.    The key to fixing flicker is realizing that the screen isn't actually
  2345.           painted in the paint() method. The pixels get put on the screen
  2346.           in the update() method which most applets don't override.
  2347.           However by overriding the update() method you can do all your
  2348.           painting in an offscreen Image and then just copy the final
  2349.           Image onto the screen with no visible flicker.
  2350.           
  2351.           The cookbook approach is simple. Add the following three
  2352.           private fields to your applet and the public update() method.
  2353.           Flicker will magically disappear.
  2354.           
  2355.  
  2356.   private Image offScreenImage;
  2357.   private Dimension offScreenSize;
  2358.   private Graphics offScreenGraphics;
  2359.  
  2360.   public final synchronized void update (Graphics g) {
  2361.  
  2362.     Dimension d = size();
  2363.     if((offScreenImage == null) || (d.width != offScreenSize.width) ||  (d.heig
  2364. ht != offScreenSize.height)) {
  2365.       offScreenImage = createImage(d.width, d.height);
  2366.       offScreenSize = d;
  2367.       offScreenGraphics = offScreenImage.getGraphics();
  2368.     }
  2369.     offScreenGraphics.clearRect(0, 0, d.width, d.height);
  2370.     paint(offScreenGraphics);
  2371.     g.drawImage(offScreenImage, 0, 0, null);
  2372.  
  2373.   }
  2374.  
  2375.   11.2: CAN YOU EXPLAIN CLASSPATH?
  2376.   
  2377.    A path specifies the name and location of a file on the file system.
  2378.           It starts with the name of the disk or the root of the
  2379.           filesystem and works its way down through various directories
  2380.           until reaches the file. File, directory, and path naming
  2381.           conventions are platform specific. For example a Unix path
  2382.           looks like /home/users/elharo/html/javafaq.html. A DOS/Windows
  2383.           path looks like C:\html\javafaq.htm. A Macintosh path looks
  2384.           like My Hard Drive:html:Java FAQ List v1.1. All three of these
  2385.           examples point to a file. Paths can also point to a directory.
  2386.           For example, /home/users/elharo/html, C:\html, or My Hard
  2387.           Drive:html:.
  2388.           
  2389.           The character that separates one directory from the next in a
  2390.           path is called the separator character. It is a slash (/) on
  2391.           Unix, a backslash (\) in Windows and a colon (:) on the Mac.
  2392.           You can get its value on a particular platform by looking at
  2393.           the static variable java.io.File.separatorCharacter.
  2394.           
  2395.           If you actually check this on the Mac, you'll note something
  2396.           funny. java.io.File.separatorCharacter appears to be a slash
  2397.           (/) like on Unix, not a colon like a Mac programmer would
  2398.           expect. Why Java had to be different from every other Mac
  2399.           program in the universe I don't know. This is problematic
  2400.           because Mac file names can include slashes.
  2401.           
  2402.           The CLASSPATH is an environment variable that contains a list
  2403.           of directories where Java looks for classes referenced in a
  2404.           program. If the CLASSPATH isn't set properly no program written
  2405.           in Java will be able to run, and the compiler won't be able to
  2406.           compile. Each entry in this list is separated from the other
  2407.           entries by the java.io.File.pathSeparatorChar. This is
  2408.           semicolon (;) on Windows and a colon (:) on Unix and the Mac.
  2409.           For example
  2410.           
  2411.  
  2412. Unix: ~/classes:/usr/local/netscape/classes
  2413. Windows: C:\java\classes;C:\netscape\classes
  2414. Mac: My Hard Drive/JDK/classes:My Hard Drive/My Project:My Hard Drive/classes
  2415.  
  2416.    
  2417.           
  2418.           On most platforms, the JDK's java interpreter appends some
  2419.           directories to the CLASSPATH you set manually. These are set
  2420.           relative to where the java interpreter itself is. For example,
  2421.           if the java program is installed in /usr/local/java/bin, then
  2422.           it will append /usr/local/java/classes and
  2423.           /usr/local/java/lib/classes.zip to the CLASSPATH. Another way
  2424.           of thinking about it: if the directory where the java
  2425.           interpreter is installed is $JAVA, then $JAVA/../classes and
  2426.           $JAVA/../lib/classes.zip are automatically in your CLASSPATH.
  2427.           
  2428.           Java applets and applications aren't self-contained. They need
  2429.           access to other classes to do their work. For instance when you
  2430.           call System.out.println() Java needs to know where to look to
  2431.           find the file that includes the System class.
  2432.           
  2433.           The directories in the CLASSPATH are where Java starts
  2434.           searching for classes. To find a class Java first changes the
  2435.           periods in the full package-qualified name of the class (e.g.
  2436.           java.util.Date and not just Date) into directory separators (/
  2437.           on Unix, \ on Windows, : on the Mac). Thus if it wants the
  2438.           java.awt.GridBagLayout class, it looks for the file
  2439.           java/awt/GridBagLayout.class in each of the root directories
  2440.           listed in the CLASSPATH variable from left to right until it
  2441.           finds the file. With the Unix CLASSPATH listed above, Java
  2442.           first looks for ~/classes/java/awt/GridBagLayout.class Then
  2443.           for, /usr/local/netscape/classes/java/awt/GridBagLayout.class.
  2444.           
  2445.           The specification of the CLASSPATH is somewhat platform
  2446.           dependent. For instance ~ means the home directory on Unix but
  2447.           has no meaning on the Mac.
  2448.           
  2449.           Under Unix you set CLASSPATH variables like this:
  2450.           
  2451. csh: % setenv CLASSPATH my_class_path
  2452. sh: % CLASSPATH=my_class_path
  2453.  
  2454.    You'll probably want to add one of these lines to your .login or
  2455.           .cshrc file so it will be automatically set every time.
  2456.           
  2457.           Under Windows you set the CLASSPATH environment variable with a
  2458.           DOS command like
  2459.           
  2460. C:\> SET CLASSPATH=C:\JDK\JAVA\CLASSES;c:\java\lib\classes.zip
  2461.  
  2462.    You can also add this to your autoexec.bat file. You should of course
  2463.           point it at whichever directories actually contain your
  2464.           classes.
  2465.           
  2466.           The CLASSPATH variable is also important when you run Java
  2467.           applets, not just when you compile them. It tells the web
  2468.           browser or applet viewer where it should look to find the
  2469.           referenced .class files. If the CLASSPATH is set improperly,
  2470.           you'll probably see messages like "Applet could not start."
  2471.           
  2472.           Since large packages can contain many, many .class files Sun
  2473.           has built the capability to read zip archives into Java.
  2474.           Therefore an entire directory structure of class files can be
  2475.           zipped to save space. If you want to see what's inside the zip
  2476.           file, unzip it. Java doesn't care whether or not a directory
  2477.           has been zipped. You just need to make sure that the .zip file
  2478.           is named the same as the directory it replaces plus the .zip
  2479.           extension and that it is in the same location.
  2480.           
  2481.           In Netscape you should make sure that the first directory in
  2482.           the CLASSPATH is the directory that contains Netscape's class
  2483.           files (The defaults are /usr/local/netscape/java/classes on
  2484.           Unix and C:\NETSCAPE\NAVIGATOR\Program\java\classes in
  2485.           Windows.)
  2486.           
  2487.           Finally note that if you install additional packages such as
  2488.           Jeeves or any third party package, you need to add the
  2489.           directory where the package is installed to your CLASSPATH. For
  2490.           example let's say you buy a package of statistics classes from
  2491.           SPSS, and you put those classes in /opt/classes/stats. Then you
  2492.           you need to add /opt/classes/stats to the end of your
  2493.           CLASSPATH.
  2494.           
  2495.           You can temporarily add a directory to the CLASSPATH by giving
  2496.           the -classpath option to the java interpreter or the javac
  2497.           compiler. For example,
  2498.           
  2499. javac -classpath $CLASSPATH:/opt/classes/stats
  2500.  
  2501.    To use just the classes in /opt/classes/stats and not the classes
  2502.           normally found in your CLASSPATH, omit $CLASSPATH like this:
  2503.           
  2504. javac -classpath /opt/classes/stats
  2505.  
  2506.    Finally if the CLASSPATH environment variable has not been set, and
  2507.           you do not specify one on the command line, then Java sets the
  2508.           CLASSPATH to the default:
  2509.           
  2510.  
  2511. Unix: .:$JAVA/classes:$JAVA/lib/classes.zip
  2512. Windows: .:$JAVA\classes:$JAVA\lib\classes.zip
  2513. Mac: ./$JAVA:classes/$JAVA:lib:classes.zip
  2514.  
  2515.    Here . is the current directory and $JAVA is the main Java directory
  2516.           where the different tools like javac were installed.
  2517.           
  2518.   11.3: WHY WON'T MY AUDIO CLIP PLAY?
  2519.   
  2520.    It's probably in the wrong format. Java 1.1 and earlier only
  2521.           understand 8 bit, mulaw-encoded, 8000 Hz, one-channel files.
  2522.           Many sound conversion programs will convert various formats to
  2523.           .au files but not necessarily to 8 bit, mulaw-encoded, 8000 Hz,
  2524.           one-channel files.
  2525.           
  2526.   11.4: WHEN I LOAD THE PAGE NETSCAPE GIVES ME A JAVA.LANG.CLASSFORMATERROR.
  2527.   
  2528.    Something is mangling the .class file. Most likely the .class files
  2529.           were uploaded to the server as text or MacBinary rather than as
  2530.           raw binary data. Make sure you put your ftp program in binary
  2531.           mode before sending the files to the server.
  2532.           
  2533.           The other possibility is that the web server is sending the
  2534.           file to clients as text rather than binary data. Make sure the
  2535.           web server is configured to send files that end in ".class"
  2536.           with a MIME type of application/octet-stream. Many web servers
  2537.           send files as type text/plain which often works but causes
  2538.           problems on a few servers. In particular, WebStar needs to
  2539.           change the action to "binary" and the MIME type to
  2540.           "application/octet-stream".
  2541.           
  2542.           It's also possible on some platforms that Netscape just can't
  2543.           find the .class file; that is, it isn't in the directory where
  2544.           Netscape is looking for it. Technically, this isn't really a
  2545.           ClassFormatError, but this is how Netscape reports it on some
  2546.           platforms and versions.
  2547.           
  2548.   11.5: NETSCAPE GIVES ME "APPLET NOT INITIALIZED ERROR"
  2549.   
  2550.    This is almost always means Netscape can't find one of the classes it
  2551.           needs to run the applet. Check to make sure that the classes
  2552.           your program uses are in the CODEBASE, the CLASSPATH, or
  2553.           somewhere else Netscape can find them. It's not uncommon to get
  2554.           this error when you first test a new package or class you've
  2555.           written with Netscape. If you've only tested it with the applet
  2556.           viewer or an IDE, then the applet viewer or the IDE may have
  2557.           included the current directory in the CLASSPATH where Netscape
  2558.           does not. Therefore the applet viewer can find the right class,
  2559.           but Netscape can't. Explicitly add the path containing your
  2560.           class or package to the CLASSPATH as specified in the previous
  2561.           question.
  2562.           
  2563.   11.6: OTHER NETSCAPE PROBLEMS
  2564.   
  2565.    As of version 3.0, Netscape has many problems handling Java applets.In
  2566.           no particular order they are:
  2567.           
  2568.           + Netscape can only run applets that are compiled with the Java
  2569.             1.0 beta compilers through the Java 1.0.2 compiler. It cannot
  2570.             handle .class files compiled for the various alpha versions
  2571.             of Java or Java 1.1. As a general rule, make sure you're
  2572.             using Sun's javac 1.0.2 to compile all applets you
  2573.             distribute. (Microsoft and Natural Intelligence's compilers
  2574.             have non-trivial bugs of their own.)
  2575.             
  2576.           + Not all versions of Netscape support Java. Notably the
  2577.             Windows 3.1 version does not, though a beta version that does
  2578.             has recently become available.
  2579.             
  2580.           + Netscape will not import any user-defined packages from the
  2581.             local CLASSPATH.
  2582.             
  2583.           + Netscape does not flush classes when you reload a page. If
  2584.             you need to reload a changed applet, for instance if you made
  2585.             a change to the applet source code and regenerated the .class
  2586.             file, there are a number of things you can try. On some
  2587.             platforms holding down the shift key and pressing the reload
  2588.             button will get Netscape to reload the .class file. You can
  2589.             also try manually clearing both the memory and disk caches,
  2590.             in order to reload an applet. Turning Java off and then on
  2591.             again in the Options/Security Preferences... menu may also do
  2592.             the trick. If none of these work, you'll simply have to quit
  2593.             and relaunch Netscape.
  2594.             
  2595.           + Netscape calls your init() method many times more than the
  2596.             appletviewer will. In particular Netscape calls init()
  2597.             anytime your reload, resize or otherwise restart your applet.
  2598.             I am not sure whether or not this is a bug, but it does
  2599.             indicate that you should try to keep your init() methods as
  2600.             small and quick as possible. Similarly it may call destroy()
  2601.             when the applet viewer would only call stop().
  2602.             
  2603.           + Netscape won't run any applet that calls Object.clone().
  2604.             
  2605.           + Netscape can't print applets.
  2606.             
  2607.   11.7: I KEEP GETTING ACCESS PRIVILEGE VIOLATIONS, " JAVA TRIED TO READ FILE
  2608.   FOO.CLASS IN DIRECTORY BAR."
  2609.   
  2610.    This happens when you try to load a class from a local hard disk
  2611.           instead of a server, the class is not a subclass of Applet, and
  2612.           the directory where the class resides is not in the HotJava
  2613.           read path. The solution is to move the class file into a
  2614.           directory in the HotJava read path. On Unix one such directory
  2615.           is ~/public_html/classes (where ~ is your home directory).
  2616.           Alternatively you can change the HOT_JAVA_READPATH environment
  2617.           variable to point to the directory containing your classes
  2618.           directory.
  2619.           
  2620.   11.8: JAVAC KEEPS INSISTING THAT IT CAN'T FIND THE RIGHT CONSTRUCTOR FUNCTION
  2621.   IN MY CLASS, BUT I'M SURE IT'S IN A FILE I IMPORTED. WHY IS IT EVEN LOOKING
  2622.   IN MY CLASS INSTEAD OF THE IMPORTED FILE?
  2623.   
  2624.    You cannot construct instances of a class on the fly using syntax like
  2625.           
  2626.           System.out.println(Double(0.56).toString());
  2627.           
  2628.           You must use the new operator like:
  2629.           
  2630. Double myDouble = new Double(0.56);
  2631. System.out.println(myDouble.toString());
  2632.  
  2633.    or
  2634.           
  2635.  
  2636. System.out.println((new Double(0.56)).toString());
  2637.  
  2638.    In other words, constructors are only called after a new operator.
  2639.           
  2640.   11.9: NULLPOINTEREXCEPTIONS WITH ARRAYS OF OBJECTS
  2641.   
  2642.    When you allocate an array of objects, each component of the array is
  2643.           initialized to null. The individual components of the array
  2644.           must still be initialized with a constructor or an assignment
  2645.           statement. For example, consider this statement:
  2646.           
  2647. Integer[] scores = new Integer[10];
  2648. int m = scores[5].intValue(); // throws NullPointerException
  2649.  
  2650.    This creates an array called scores containing ten references to
  2651.           Integer objects. Then it tries to get the value of the fifth
  2652.           component. However, each of those references is initially set
  2653.           to null. Thus when you try to call a method on one of the
  2654.           components of the array or pass the component to a method that
  2655.           expects a non-null argument, a NullPointerException is thrown.
  2656.           
  2657.           To fix this, you need to initialize the components of the
  2658.           array, either with constructors or with assignment statements
  2659.           For example:
  2660.           
  2661. Integer[] scores = new Integer[10];
  2662. for (int i = 0; i < scores.length; i++) scores[i] = new Integer(i);
  2663. int m = scores[5].intValue();
  2664.  
  2665.    You do not need to initialize all the components of the array though
  2666.           it's a good idea to do so. You can initialize just those you'll
  2667.           use, or you can make sure you catch and handle
  2668.           NullPointerExceptions in the appropriate places.
  2669.           
  2670.           This is different from how Java handles uninitialized non-array
  2671.           reference variables. By way of contrast when you write,
  2672.           
  2673. Integer score;
  2674. int m = score.intValue();
  2675.  
  2676.    the compiler catches the null reference in score and complains. You
  2677.           have to fix the problem before you can compile the program.
  2678.           However in general the compiler has no way to know whether an
  2679.           array component has or has not been initialized. Therefore the
  2680.           check for the non-nullness of an array component is deferred
  2681.           till runtime when the NullPointerException may be thrown.
  2682.           
  2683.   11.10: CAN'T MAKE STATIC REFERENCE TO METHOD TYPE MYMETHOD IN CLASS MYCLASS
  2684.   
  2685.    This common error occurs when you attempt to call an instance method
  2686.           from a static method, most commonly main(). For example,
  2687.           
  2688. class StaticTest {
  2689.  
  2690.   public static void main(String[] args) {
  2691.  
  2692.     int i = getX();
  2693.  
  2694.   }
  2695.  
  2696.   public int getX() {
  2697.  
  2698.     return 3;
  2699.  
  2700.   }
  2701.  
  2702. }
  2703.  
  2704.    The static method, main(), belongs to the class. However, getX()
  2705.           belongs to an object in the class. The compiler doesn't know on
  2706.           which object it's invoking the getX() method.
  2707.           
  2708.           There are a couple of ways around this problem. You could
  2709.           declare that getX() is also static; that is:
  2710.           
  2711.           public static int getX() {
  2712.           
  2713.           Alternately, you can instantiate an object in the StaticTest
  2714.           class in the main() method and invoke that object's getX()
  2715.           method, like this:
  2716.           
  2717.   public static void main(String[] args) {
  2718.  
  2719.     StaticTest st = new StaticTest();
  2720.     int i = st.getX();
  2721.  
  2722.   }
  2723.  
  2724.   11.11: WHY DO I HAVE TROUBLE WHEN USING == TO COMPARE STRINGS?
  2725.   
  2726.    When used on objects, == tests whether the two objects are the same
  2727.           object, not whether they have the same value. Consider this
  2728.           code fragment:
  2729.           
  2730.         String s1 = new String("Hello World");
  2731.         String s2 = new String("Hello World");
  2732.         if (s1 == s2) {
  2733.           System.out.println("The strings are the same.");
  2734.         }
  2735.         else {
  2736.           System.out.println("The strings are different.");
  2737.         }
  2738.  
  2739.    This prints "The strings are different."
  2740.           
  2741.           To compare to objects for equality, rather than identity, you
  2742.           should use the equals() method, like this:
  2743.           
  2744.         String s1 = new String("Hello World");
  2745.         String s2 = new String("Hello World");
  2746.         if (s1.equals(s2)) {
  2747.           System.out.println("The strings are the same.");
  2748.         }
  2749.         else {
  2750.           System.out.println("The strings are different.");
  2751.         }
  2752.  
  2753.    This prints "The strings are the same." The default equals() method
  2754.           all objects inherit from java.lang.Object just tests for object
  2755.           identity with ==. However many classes, including
  2756.           java.lang.String, override equals() to test the state of the
  2757.           object.
  2758.           
  2759.           However, the issue is a little confused when string literals
  2760.           are considered. Consider this code fragment:
  2761.           
  2762.         String s1 = "Hello World";
  2763.         String s2 = "Hello World";
  2764.         if (s1 == s2) {
  2765.           System.out.println("The strings are the same");
  2766.         }
  2767.         else {
  2768.           System.out.println("The strings are different");
  2769.         }
  2770.  
  2771.    This prints "The strings are the same". The compiler recognizes that
  2772.           the two string literals have the same value and it performs a
  2773.           simple optimization of only creating one String object. Thus s1
  2774.           and s2 both refer to the same object and are therefore equal.
  2775.           The Java Language Specification requires this behavior.
  2776.           However, not all compilers get this right so in practice this
  2777.           behavior here is implementation dependent.
  2778.           
  2779. 12: Security
  2780.  
  2781.   12.1: SYSTEM LEVEL SECURITY
  2782.   
  2783.    On a system level Java applets live in a cage. They can do pretty much
  2784.           anything they want inside their cage, but they cannot get
  2785.           outside the cage and do damage unless the user unlocks the door
  2786.           to the cage. Even then they wear shackles that prevent them
  2787.           from doing things like writing to arbitrary addresses in
  2788.           memory.
  2789.           
  2790.           In Netscape the user doesn't even get the keys to the cage so
  2791.           you can't let the applets out into your system even if you
  2792.           wanted to. With the Applet Viewer it is possible to give your
  2793.           applets more access to the network. However they still can't do
  2794.           everything a C program can do.
  2795.           
  2796.           Specifically a Java applet cannot write anything to a hard
  2797.           drive. It cannot write directly to memory, and it cannot
  2798.           introduce a virus into your system. A Java applet can use a lot
  2799.           of your CPU time though not 100% of it. It cannot crash your
  2800.           system (though a Java enabled browser can).
  2801.           
  2802.   12.2: USER LEVEL SECURITY
  2803.   
  2804.    A Java applet can trick the user into doing something stupid such as
  2805.           revealing their root password though there are efforts to avoid
  2806.           this. A Java applet can also send this information back to the
  2807.           applet's server.
  2808.           
  2809.           Finally an applet can display pictures or text or play sounds
  2810.           which the user may find annoying or offensive, but this hardly
  2811.           qualifies as a security flaw and is not unique to Java enabled
  2812.           browsers.
  2813.           
  2814. 13: Tools
  2815.  
  2816.   13.1: IDE
  2817.   
  2818.    Symantec publishes Cafe and Visual Cafe, an applet development
  2819.           environment for Windows 95, NT and the Mac. It includes a
  2820.           source code editor and a class browser, and a just-in-time
  2821.           compiler. It is still beta quality at best. I do not recommend
  2822.           it.
  2823.           
  2824.           Natural Intelligence's Roaster is a Macintosh hosted applet
  2825.           development environment. It is also still beta quality. I do
  2826.           not recommend it.
  2827.           
  2828.           Metrowerks includes Java support in Code Warrior Gold.
  2829.           Metrowerks has licensed Sun's source code. The Java support is
  2830.           alpha quality, and is not by itself worth the price of Code
  2831.           Warrior, even the $99 Java only edition. However if you also
  2832.           need a C compiler it doesn't cost you anymore to get Java
  2833.           support.
  2834.           
  2835.           Sun publishes a payware IDE called Java Workshop. It is fairly
  2836.           cheap, ($99) but again not yet worth the download time. Java
  2837.           Workshop is similar to Sun's existing Workshop products for
  2838.           Fortran and C++. However it is written entirely in Java. You'll
  2839.           need at least a Pentium Pro to squeeze adequate performance out
  2840.           of this system.
  2841.           
  2842.           Microsoft's Visual J++ is one of the faster VM/JIT combinations
  2843.           available. However the compiler has some bugs that prevent it
  2844.           from compiling certain legal Java code. Once again this is beta
  2845.           software at best, and is not worth spending money on.
  2846.           
  2847.           Borland's JBuilder has gotten some nice reviews, but I've yet
  2848.           to try it personally. Furthermore, their lawyers seem to be out
  2849.           of control.
  2850.           
  2851.           The bottom line is that you should use Sun's JDK (or your local
  2852.           platform's equivalent) and the text editor of your choice. None
  2853.           of the available IDEs are worth what they cost. All will cause
  2854.           you more problems than they solve. Unless you enjoy paying to
  2855.           beta test products, there's no reason to purchase any of these
  2856.           products at this time.
  2857.           
  2858.   13.2: DEBUGGER
  2859.   
  2860.    A preliminary jdb is available with Java Developer's Kit from Sun.
  2861.           Various payware IDEs include debuggers of beta quality at best.
  2862.           
  2863.   13.3: EDITORS
  2864.   
  2865.    I use BBEdit 4.0 on the Mac. The free, light version works well too
  2866.           although it doesn't include syntax coloring. See
  2867.           
  2868.           http://www.barebones.com/bbedit.html
  2869.           
  2870.           However, in general any normal text or programmer's editor
  2871.           should be fine.
  2872.           
  2873.           The Windows Notepad program, however, is not fine. It appends
  2874.           the extension ".txt" to all files it saves. Java source code
  2875.           files must end in ".java". If you must use Notepad, enclose the
  2876.           filename in double quotes when you save it; that is don't just
  2877.           type HelloWorld.java but rather "HelloWorld.java". This will
  2878.           force Notepad not to append a ".txt" extension to the file.
  2879.           
  2880.   13.4: YACC GRAMMAR
  2881.   
  2882.    An LALR grammar for Java is included in The Java Language
  2883.           Specification.
  2884.           
  2885.   13.5: PROFILERS
  2886.   
  2887.    Using the -prof option to the java interpreter produces basic profile
  2888.           information in a file called java.prof. That is,
  2889.           
  2890.           % java -prof HelloWorld.class
  2891.           
  2892. 14: The Java Virtual Machine and Byte Codes
  2893.  
  2894.    The most recent Java Class File / Java Virtual Machine specs are
  2895.           available in various formats from
  2896.           http://www.javasoft.com/java.sun.com/newdocs.html
  2897.           
  2898.   14.1: CAN I PROGRAM DIRECTLY IN BYTE CODE?
  2899.   
  2900.    Yes, you can. Jonathan Meyer's Jasmin Java assembler is a small
  2901.           assembler for Java byte code, and would be of great assistance
  2902.           to you in such an endeavor. The Java interpreter will check
  2903.           your byte codes to make sure they don't violate security. If
  2904.           you write security violating byte codes the interpreter won't
  2905.           run them.
  2906.           
  2907. 14.2: Optimizing Java
  2908.  
  2909.          1. Make your classes final.
  2910.             
  2911.          2. Use the -O flag to the compiler.
  2912.             
  2913.          3. If you're reading data off a disk read it in as large a chunk
  2914.             as possible. Do not read it a byte at a time. If you need to
  2915.             process the data a byte at a time read it into a temporary
  2916.             buffer first.
  2917.             
  2918.          4. Creating objects is expensive. Try to reuse objects rather
  2919.             than creating new ones, especially for temporary objects that
  2920.             exist only to support a calculation.
  2921.             
  2922.          5. Avoid synchronization where possible.
  2923.             
  2924.    
  2925.           
  2926. 14.3: Disassembly, Decompilation, and Obfuscation
  2927.  
  2928.    Compiled Java byte code is comparatively trivial to disassemble, and
  2929.           it's not that much harder to decompile. The javap program
  2930.           included in the JDK disassembles .class files into reasonably
  2931.           legible, assembly like code. For example,
  2932.           
  2933. % javap -c HelloWorld
  2934. Compiled from HelloWorld.java
  2935. class HelloWorld extends java.lang.Object {
  2936.     public static void main(java.lang.String[]);
  2937.     public HelloWorld();
  2938. }
  2939.  
  2940.  
  2941. Method void main(java.lang.String[])
  2942.    0 getstatic #7 <Field java.io.PrintStream out>
  2943.    3 ldc #1 <String "Hello World!">
  2944.    5 invokevirtual #6 <Method void println(java.lang.String)>
  2945.    8 return
  2946.  
  2947.  
  2948. Method HelloWorld()
  2949.    0 aload_0
  2950.    1 invokespecial #8 <Method java.lang.Object()>
  2951.    4 return
  2952.  
  2953.  
  2954.    While this isn't the original source code, it's enough for experienced
  2955.           programmers to understand, especially if they have a copy of
  2956.           the Java Virtual Machine Specification in hand.
  2957.           
  2958.           There are also third party decompilers that go a step further
  2959.           and produce something very close to the actual source code. The
  2960.           first was Mocha by the late HanPeter van Vliet, although this
  2961.           is beginning to show its age. (In yet another tale of lawyers
  2962.           run wild, Borland is trying to retroactively change the Mocha
  2963.           license agreement.) SourceTec's Jasmine is a $29.80 shareware
  2964.           decompiler. Wingsoft's WingDIS is a $39.95 payware decompiler.
  2965.           A free copy of WingDIS 2.0.3 is included in the CD with my book
  2966.           Java Secrets (IDG Books, 1997).
  2967.           
  2968.           Obfuscator or shrouder tools play various tricks with the
  2969.           compiled byte code in a .class file, especially with private
  2970.           field and method names, to attempt to confuse these tools.
  2971.           However Java's late binding places severe limits on how much
  2972.           these tools can do, especially in class libraries and other
  2973.           component software.
  2974.           
  2975.           To the best of my knowledge the first such tool developed was
  2976.           HanPeter van Vliet's payware Crema, though there's evidence
  2977.           that IBM may have developed a similar tool internally around
  2978.           the same time but never released it to the public. A version of
  2979.           Crema has been incorporated into Borland's JBuilder.
  2980.           
  2981.           Other obfuscators include K.B. Sriram's Hashjava (distributed
  2982.           under the GNU Library General Public License (LGPL).), Eron
  2983.           Jokipii's Jobe (free for non-commercial use), and Eastridge
  2984.           Technology's $45 payware Jshrink.
  2985.           
  2986. 15: Legal Issues
  2987.  
  2988.    Some portions of Java and HotJava are neither in the public domain nor
  2989.           copylefted. However no license is required to write and
  2990.           distribute most Java applications and applets. Nor is any
  2991.           license from Sun is required to distribute the Java or HotJava
  2992.           in binary form.
  2993.           
  2994.           The source code for Java is freely available for non-commercial
  2995.           use though a license must be signed. Source code for the java
  2996.           packages is included with the various versions of the JDK,
  2997.           including 1.1. However, if you want to license the Java source
  2998.           code for commercial use, you will need to negotiate a source
  2999.           code license with Sun. Complete details are at
  3000.           http://www.javasoft.com/java.sun.com/source.html.
  3001.           
  3002.           Furthermore whether your product is commercial or
  3003.           non-commercial you may not use the trademark "Java" to describe
  3004.           your product unless you pass an as yet unreleased verification
  3005.           and test suite.
  3006.           
  3007. 16: FAQ's about the FAQ
  3008.  
  3009.   16.1: WHO IS THIS ELLIOTTE GUY, AND JUST WHAT QUALIFIED HIM TO WRITE A JAVA
  3010.   FAQ ANYWAY?
  3011.   
  3012.    He was willing to do it. Seriously, months on the Java mailing lists
  3013.           made it obvious that a FAQ was needed and since none seemed to
  3014.           be forthcoming from those more qualified than I, I boldly and
  3015.           with a complete disregard for my absolute lack of
  3016.           qualifications stepped forward and volunteered. I do have some
  3017.           hope that my previous experience with FAQ lists, the World Wide
  3018.           Web and a variety of programming languages may somehow cover up
  3019.           the fact that I have no idea what I'm doing. You've read the
  3020.           FAQ list by now. Did I succeed?
  3021.           
  3022.           Why am I taking on such a Herculean task? It's often said that
  3023.           you never really understand a subject until you teach it. I'm
  3024.           going to endeavor to learn Java and understand it by teaching
  3025.           it. The result should be interesting at least. Since I'm very
  3026.           new to Java and clearly do not yet understand the language,
  3027.           I'll have a perspective on the issues that should be helpful to
  3028.           newcomers.
  3029.           
  3030.           Are there mistakes here? Absolutely. I hope people here and
  3031.           elsewhere will correct me gently and help lead me on the path
  3032.           to true Java enlightenment when I err. And if they aren't so
  3033.           gentle, well, I've developed a pretty thick skin after six
  3034.           years of Usenet.
  3035.           
  3036.           My companion tutorial in how to write Java is going to reflect
  3037.           the programs I'm actually writing. As I learn to do a Hello
  3038.           World program, I'll write about Hello World. (OK, I've actually
  3039.           already gotten beyond Hello World but not much beyond.) How
  3040.           fast the FAQ list grows will depend in large part on how fast
  3041.           my skills grow. You'll get to watch me learn, make mistakes,
  3042.           correct mistakes and so on.
  3043.           
  3044.           There may be an advantage to this approach. People who want to
  3045.           learn Java will be coming from almost identical places as me. I
  3046.           always hate having to write down or talk down to people, and I
  3047.           don't do it very well. Similarly I find it frustrating to try
  3048.           to communicate with people who are way beyond me (as obviously
  3049.           some people on the Java mailing lists are). This means that I
  3050.           can write for people without much prior experience without
  3051.           boring myself or, hopefully, my audience, to tears.
  3052.           
  3053.           Finally I'll emphasize that I'm not trying to prevent anyone
  3054.           else or any other team of people from taking on a similar
  3055.           project. I hope someone does. I'll probably learn from what
  3056.           they do, and they'll learn from what I do, even if it's only to
  3057.           learn the sorts of things novices are confused about. And of
  3058.           course not everyone shares the same learning style so while
  3059.           some people may enjoy my approach to Java I am sure others will
  3060.           find it dense, incoherent, and ultimately incomprehensible.
  3061.           More choices are better.
  3062.           
  3063.           Ultimately I'm doing this because I think Java is very, very
  3064.           cool and I am convinced I need to learn it sooner rather than
  3065.           later. I think this project will propel my Java knowledge
  3066.           forward, and if it does that I'll consider my project a
  3067.           success. If I can help a few other lost souls to climb out of
  3068.           the pit with me at the same time, so much the better.
  3069.           
  3070.   16.2: WHY DON'T YOU INCLUDE X IN YOUR FAQ?
  3071.   
  3072.    Please do make suggestions about topics for FAQ list inclusion. You
  3073.           can email them to elharo@sunsite.unc.edu. I do follow the
  3074.           various comp.lang.java groups as best I can, and have a pretty
  3075.           good idea of what's discussed there.
  3076.           
  3077.   16.3: THIS IS REALLY COOL. CAN I REPUBLISH OR TRANSLATE IT?
  3078.   
  3079.    This FAQ list and its entire contents are copyright 1995-1997 by
  3080.           Elliotte Rusty Harold. If you have specific desires to
  3081.           republish it in whole or part contact me at
  3082.           elharo@sunsite.unc.edu and tell me exactly what you want to
  3083.           do. I'm generally receptive to non-profits that want to make it
  3084.           available to the public at no charge and to anyone who's
  3085.           willing to make reasonable payment arrangements.
  3086.           
  3087.           However I do not allow the FAQ list, either the text or HTML
  3088.           version, to be placed on any web or ftp sites but my own.
  3089.           Mirroring HTML files is a fundamentally bad idea that is at
  3090.           cross-purposes with the design of the web. Among other problems
  3091.           it makes maintaining up-to-date copies phenomenally difficult.
  3092.           If you think this file would be a useful addition to your web
  3093.           site, then link to it. That's the way the web is designed. Not
  3094.           all information needs to reside in one central location. No
  3095.           permission is needed to link to this or any other of my HTML
  3096.           files. In fact I'd prefer it if you'd not ask me, since then I
  3097.           don't have to spend time answering you.
  3098.           
  3099.           Although there's more reason to want to translate the document
  3100.           rather than merely mirror it, I regret that I do not have the
  3101.           time or resources to support any translation efforts, and
  3102.           therefore do not currently allow this FAQ list to be translated
  3103.           into other languages. This document will be available in
  3104.           English only for the foreseeable future.
  3105.           
  3106.           If you want to use the source code samples included here,
  3107.           please do. I consider the source code (though not the FAQ list
  3108.           itself!) to be public domain. No permission is necessary to
  3109.           reuse, edit, modify or publish any of the source code contained
  3110.           in this FAQ list.
  3111.           
  3112. --           
  3113.           Copyright 1995-1997 Elliotte Rusty Harold
  3114.           elharo@sunsite.unc.edu
  3115.           Last Modified October 6, 1997
  3116. -- 
  3117. Elliotte Rusty Harold     
  3118. elharo@sunsite.unc.edu    
  3119. elharo@shock.njit.edu 
  3120.