Select this to skip to main content [CSUSB] >> [CNS] >> [Comp Sci Dept] >> [R J Botting] >> [CS320 Course Materials] >> [Java] >> java [Source]
[Index] [Schedule] [Syllabi] [Text] [Labs] [Projects] [Resources] [Search] [Grading]
Thu Jan 22 13:43:06 PST 2004


    The Java Programming Language

      This page plus the [ CS320 Labs ] are designed to be a step by step introduction to Java for a competent C++ programmer. Getting your first Java programs to run is unusually hard because

      1. Names of files have to precisely match the identifiers used inside the files.
      2. Some books do not follow the newer scoping rules.

      (End of Net)
      Beginners should work through the [ Overview ] and [ Java at CSCI.CSUSB.EDU ] sections below to make this process less painful.


      Please contact me at if you have any comments, suggestions, corrections etc.

      Pointers to WWW information on the Java Language

      1. (FAQ): [ faq ] [ javafaq.html ] [ javafaq ] local: [ java.FAQ.html ]
      2. (News): [ java.www.sites.html ] [ ] alt.www.hotjava comp.lang.javascript
      3. (Samples): local: [ ]

        remote: [ ~espresso ] [ ] [ phoneCase.html ] [ wallstreetweb ] [ index.html ] [ ] [ ] [ ] [ algintro.html ] [ index.html ]

      4. (Documentation): local: [ Glossary ] [ java.class.tree.html ] [ java.classes.html ] [ java.glossary.html ] [ java.html ] [ java.lang.System.html ] [ java.packages.html ] [ java.semantics.html ] [ java.syntax.html ] [ java.www.sites.html ] [ See Also ]

        remote: [ ] = [ ] = [ ] , . . . For more general information see the Java and HotJava Documentation [ documentation.html ] and in particular the goals of Java [ index.html ] and the Java Tutorial at [ ] or download // and unzip it into a HTML page.

        A programmer's guide: [ index.html ]

      . . . . . . . . . ( end of section Pointers to WWW information on the Java Language) <<Contents | Index>>

      Java at CSCI.CSUSB.EDU

      If you are not interested in our local set-up please see the Overview section below.

      We have the Java Development Kit (JDK) version 1.0 with its compiler, interpreters, library packages, documenter, and disassembler on the Sun Workstations in JB358 and Orion. The binaries, libraries etc are in /usr/local/java. The compiler and interpreter (javac & java) figure out where the classes are relative to this directory. All the Java tools can be run by typing in their name and the right arguments, as long as you are on a Sun and have /usr/local/bin in your PATH. I have programmed 'Q'/'quickie' to compile, document, and interpret Java applications for users of the Sun systems here.

      JDK1.1 (same language but newer library classes) can be found on the Suns at

    1. /usr/local/jdk1.1.5/

      Dr. Zemoudeh, on Mar 2nd, made JDK 1.1.3 avaible for Silicon Graphics machines. It is on Indigo and all the workstations in the SGI lab. The tools are in /usr/local/java/bin. They include the appletviewer, java, javac, javap, javadoc as described in this document and a number of other things like the Java Debugger (jdb). As long as your .profile sets your PATH to include either /usr/local/bin or /share/bin all the commands noted below should be found and executed ok. The Q/quickie commands on SGIs will also do quick ompilation and test runs.

      There is some documentation pages available on the SGIs that can be read locally, on an SGI, by Netscape. Use Netscape's File menu to Open file...

      on an SGI.

      The /public directory on Orion, Indigo, and the SGI workstations is an ideal site on the World Wide Web for Java files and Web Pages. It is the same data whether you use Orion or an SGI to access it. Each user with an HOME directory like this /u/group/user_name has a public directory like this: /public/group/user_name. Files have URL's that start "" See my 'how-to-publish' guide [ publishing ] for more information.


        Java is a strongly object-oriented programming language designed originally for use in consumer appliances like VCRs and toasters. It is designed with concurrent programming in mind. It has most of the control structures of C but without "go to" and with exceptions.

        It is based on the first version of C++ but explicitly leaves out features of C and C++ that are confusing or unreliable. It has inheritance and dynamic polymorphism but not generic templates. In time these will be added to Java.

        Java comes with a large library of ready made classes and objects. The key difference betwen Java 1.0 and 1.1 was in this library. - the AWT.

        A C++ programer will find Java programs easy to read. Java is more verbose than C++ however and so slightly harder to write. Java is compiled into a special machine code that is then interpreted. So it does not perform as fast as C++. However a Java program can be transmitted across a network to a machine of a different type, with a different operating system, and different graphic user interface. There it will run safely and securely (in theory) and look-and-feel as if it was programmed for that system. In theory you can not do this with C++.

        Java can be used to write applications and applets. A Java application is similar to any other high-level language program in that it is compiled and then run on the same machine. An applet is compiled on one machine, stored on a server in binary, and is then sent to a another machine over the Internet to be interpretted by a Java-aware browser.


          An application is compiled (using javac) and run like any other program but it is actually a Java class that contains a special method called 'main'. When the interpreter (java) is called with the name of the class, it looks for the public static main(String[]) function in the class and calls it.

          Example Application

          The following is based on the old traditional C program that prints "Hello, World" on the computer screen:
        1. (Hello):
             	import java.lang.*;
             	public class Hello {
             	    public static void main(String argv[]){
             	        System.out.println("Hello, World!");

          The above is best put in a file called [ ]

          The import statement in a Java file allow it to refer to other classes in other files and directories. The compiler uses these other classes's definitions to check your code, and the interpreter loads the binary bytecode into the running program.

          The word public means that the thing following it can be accessed by anyone. A public class can be imported over the internet into any other class and so can be sent to a browser. A public function can be called by statements and expressions in different classes.

          static indicates that a function or object belongs to the class rather than to each individual object in the class.

          For an example of a simple and useless Java application and its documentation see [ ] and [ Luv.html ] These applications are part of the first CS320 lab.

          Notice that Java code was designed to be interpreted by a machine independent virtual machine (JVM) that runs a special machine code called bytecode.

        . . . . . . . . . ( end of section Applications) <<Contents | Index>>


        The Hello application would be compiled like this:
        and run by the java interpreter like this:
         		 java Hello
        Notice that the file "" is compiled, but a class is interpreted. One nice feature of the Sun JDK is the documentation tool javadoc. The above application Hello has the following documentation: [ Hello.html ] which was generated by javadoc.

        javadoc scans source code files (*.java) and creates one HTML file per class in the files. Classes and parts of classes can have special documentary comments (starting "/**" ) added to them that are reformatted and incorporated into the Hypertext produced by javadoc. This should be a boon for realistic projects. The full syntax of the special comments can be as [ Doc_Comment in java.syntax ] in this web site.

        The javap program disassembles bytecode (*.class files) and outputs a description of the what is in them javap.


          An Applet is a small program that can be sent across the Internet and interpreted on a client machine. To give permission for remote access it must be a public class. Typically it is a class that inherits and/or defines a special set of functions needed to run an applet. These are part of the class Applet. So all Java applets are public classes that extend Applet.

          The compiled '.class' file for an applet is named in a Web Page [ www.html ] written in the HyperText Markup Language(HTML) [ comp.html.syntax.html] .

          You can not run a Java applet unless it is also an applications or you have a WWW page that refers to it. The page needs HTML like the following to call the compiled code, in the same directory:

                    <APPLET CODE="ClassName.class" HEIGHT=h WIDTH=w>
          		Alternate text
          where h and w are the HEIGHT and WIDTH of the box in which the applet outputs its response. The alternate text appears when a browser can not handle APPLETs. For the general syntax see applet_in_html. The code in "ClassName.class" above, is the result of compiling a file called "" that contains a public class called ClassName which extends an Applet.


          Here is a suitable piece of HTML to test a simple HelloWorld class:
                    <APPLET CODE="HelloWorld.class" HEIGHT=150 WIDTH=150>
           		You can not see this brilliant Java Applet.
          Put this in a file called:

          The code for the HelloWorld applet has to be a public class called "HelloWorld" that extends Applet and is in in a Java file called:

          Here is the Java code:
        1. (HelloWorld):
             	import java.applet.*;
             	import java.awt.*;
            	public class HelloWorld extends Applet {
            	      public void init() {
            	      public void paint(Graphics g) {
            	          g.drawString("Hello world!", 50, 25);

          The Applet is compiled just like any other program:

          This will generate a set of files with extension/suffix ".class". Notice that the compiler forces you to name the file "", the Class "HelloWorld", and generates the binary bytecode in a file called "HelloWorld.class". javadoc scans the "" and creates "HelloWorld.html". Sun has written a special program to test applets in page:
                    appletviewer test.HelloWorld.html
          However you can not use 'java' to run the HelloWorld class - it has no 'main'. Neither can 'java' "run" the WWW pages like the test.HelloWorld.html file.

          On the Suns in the Sun lab you can tell 'Netscape' to "Open local File..." and select

          but using Netscape to debug an applet has some problems indicated later.


          The moment a .class file or a package becomes public on the web, other Java classes, anywhere on the web, can "import" your public classes and use them to construct more classes!

          Normally you should put applet code (compiled and source) in the same directory as the public page that refers to them. This is simple and works.

          For example, here at you develop the code, documentation, and test page for HelloWorld in your home directory. You can then just input this command

           		publish *HelloWorld*
          and all the files (the test page, the class, the code, and any documentation) are all made public. Netscape on any machine can now be pointed at your test page:
           		netscape http:/public/group/your_id/test.HelloWorld.html
          For more information on publish see [ publishing ]

          There are more complicated ways of organizing the files. It is said that if the page is in directory with path name D on the server and your operating system uses S to separate directories in path names

          	( S.DOS=`\`, S.UNIX=`/`, S.Mac=`:`)
          then the applet code for class C must be in directory DSclasses and have a name C.class. However Netscape 2.01 for Suns looks in directory D, unless you add the attribute CODEBASE=classes to the Applet tag.

          Problems with Netscape

          • To be sure of a browser finding all the necessary class files they have to be in the same directory as the pages that refer to them. You can not keep the bytecode .class file private and the page public. To put .class files in a subdirectory you may have to place them in a package with the same name.

          • If the Applet fails, use the Options menu to open the Java Console... and look for errors.

          • Netscape does not make a good development tool because it is hard to make the program reload the code of Applets. You can change the code, recompile it, publish all the files perfectly, and hit the reload button in Netscape and it will not reload the new bytecode. I've wasted hours looking for bugs that I've fixed. Instead use Sun's appletviewer and/or debuggers. You can also include a main function in applets that make them applications. See [ Applications Can Run Applets ] next.

          Applications Can Run Applets

          The 'java' interpreter can run classes that have an appropriate 'main' function:
          	java classname
          This special method or function is called main. To run an applet it must create a window and run the applet in it. The steps are:
          1. Create a new window to display the applet.
          2. Create a new object of the correct class.
          3. Tell the applet to initialize itself.
          4. Tell the applet to start running.
          5. Add the running applet into the window.
          6. Resize the window.
          7. Show the window to you.

          Please use the following sample as a model for your own testing:
               public static void main(String args[]) {
           		Frame aWindow = new Frame("HelloWorld");
           			//A window called "HelloWorld" will hold the Applet
           		HelloWorld aHelloWorldObject = new HelloWorld();
           			//The object that will be put in the window
           			//HelloWorld has now initialized it self
           			//HelloWorld has now started running
           		aWindow.add("Center", aHelloWorldObject);
           			//aWindow now has HelloWorld in it's center
           		aWindow.resize(SIZE, SIZE);
           			//aWindow is now shown to you (until you CTRL/C)
           	   private final static int SIZE = 300;
          You can download an uptodate working copy of the HelloWorld class which is both an applications and and applet from [ ] Keep a copy of this and use it generate your own test programs for applets.... before you put them on the Web!

          I have just developed a new tool that will generate an HTML test page for a new applet and also a suitable *.java file ready for the details to be filled in It is in [ instantapplet ] and tap return. 'instantapplet' is in Beta-testing.

        . . . . . . . . . ( end of section Applets) <<Contents | Index>> There is a more elaborate example of a Java applet/application program in [ Goodbye.html ] complete with links to the source code, documentation, and byte code.

      . . . . . . . . . ( end of section Overview) <<Contents | Index>>


      Class NameC
      Applicationpublic class C { ... public static void main(String[])...}
      Appletpublic class C extends Applet { ... }
      javac C.javacompiled into:
      javadoc C.javaproduces C.html


        Also see [ java.glossary.html ] [ gloss.htm ]

      1. abstract::methods=A method that must exist for objects in a class but is fully defined only in subclasses,
      2. abstract::classes=A class with one or more abstract methods.

      3. Applet::AWT=Class of objects that are embedded in an HTML page and initialized and run by a browser over the WWW
      4. applet::=A small program that can be sent across a network and interpreted safely on the receiving machine.

      5. application::Java=A class that defines a public static void main(String args[]) method

      6. AWT::=awt.
      7. awt::=Abstract windowing toolkit, another windowing toolkit. A set of machine independent classes that make it easier to create graphic user interfaces and output.

      8. bytecode::= [ byte_code] .
      9. byte_code::=a way of describing classes as a stream of byte oriented machine code for the Java Virtual Machine.

      10. classes::=plural of class.
      11. class::=A set of objects with similar behaviors and intelligence. A class defines a collection of knowledge and know how. Classes are defined by declaring variables and and functions.. [ class in objects.glossary ]

      12. constant::=any final field -- a piece of data about an object or class that can not be varied once it is initialized.

      13. extends::=indicates that a new class has all the properties of the class it extends. In Java all classes ultimately extend the class Object.

      14. field::java=A variable or constant associated with a class or object - a piece of data or knowledge that that object knows about and controls.

      15. file::=A collection of data. A Java source code file defines one or more classes, interfaces that is placed in a particular package.

      16. final::modifier=a final class can not be extended, a final variable can not have its value changed, and a final function can not be overridden.

      17. function::computing=A named piece of code that returns a value and may also do something
      18. function::java=A piece of know-how attached to a class or accessed via an object

      19. implements::=indicates that a class defines all the public functions listed in an interface.

      20. interface::=The way that something is accessed from outside. The parts of an object that are shared with the clients that use that object.
      21. interface::java=A collection of abstract public function headers that can be implemented in different ways by different classes, and extended to give more interfaces..
      22. interface::=Describes a set of classes in terms of what they can do for you, but allows each class to implement these methods in any way that you wish.

      23. Java::=A language developed by Sun for developing software that is distributed over the Internet to special purpose hardware like a thermostat or (latterly) to browsers via the WWW.

      24. JDK::=Java Development Kit( compiler=> javac, interpreter=> java, classes=> AWT.

      25. JVM::=Java Virtual Machine, the virtual_machine provides the operational semantics of Java and so defines the hardware+software environment needed to run Java bytecode.

      26. methods::=plural of method.
      27. method::=A piece of "know-how". A procedure or function that is associated with an object or a class.

      28. modifier::=public | static | final | private | protected | abstract | ..., a word placed in front of a declaration that changes its semantics.

      29. object::=An instance of a class, in Java an object is always handled via a reference that is created by the 'new' operation and a constructor and can be assigned to field of that class.

      30. procedure::ComputerScience=`A named piece of code that does something for a caller'.
      31. procedure::java=a void function.

      32. public::modifier=indicates that a class, field, or function can be used by anything and anywhere on the internet.

      33. private::modifier=indicates that a class, field, or function can only be used locally inside a class.

      34. protected::modifier=A degree of hiding lie between public and private. -- deprecated!

      35. package::=a collection of classes, encode as files in a common directory, that has the same name as the package and are allowed special access privileges. The default scope/access for a function or class is to its package. If no package is declared at the start of a file then the classes etc belong in the deafult global package.

      36. static::=something associated with a class rather than an object.

      37. variable::java=A piece of knowledge associated with a class or an object. Any non-final field.

      38. virtual_machine::=A hypothetical machine that can be emulated on many different actual machines.

      39. void::=word used in place of a type to indicate that a function does not return a value. -- introduced in ANSI C and still confusing people 10 years later.

      40. WWW::="World Wide Web".

      41. URL::="Universal Resource Locator'.

        Also see [ java.glossary.html ]

      . . . . . . . . . ( end of section Glossary) <<Contents | Index>>


        The syntax of Java is close to C++ but a lot more verbose.
      1. syntax::= See

        In outline a java file starts with an optional package declaration and some import statements:

         	package whatever;
          import package.subpackake.class
          import packack.package.*
        These are followed by a sequence of class and interface declarations:
         		modifiers name extends class possible_interfaces{
         			field and function definitions

        Field definitions have two forms:

         		modifiers type name;
         		modifiers type name = initial value;
        wehre a type is either a classname or a simple data type like 'int' or 'char' or 'double'. If the modifiers include 'final' then the field is a constant, othewise it is a variable. The following is a very common and useful declaration:
         		modifiers type name = new name(arguments);

        Arrays are declared like this:

         		modifiers type name[];
         		modifiers type name[] = new type[size];
        In the first case the array must not be used until it is initialised in a staement like this:
         		 name = new type[size];
        Further if the 'type' is a class, the individual objects must be constructed and put in the array before they are used.

        Function definitions have form

         		modifiers return_type name(arguments){
        			field definitions and statemants
        the return_type above is "void" or the name of a class or simple data type. modifiers are listed in the glossary.

        Statements have following main forms:

         		variable = expression;
         		while(expression) statement
         		if(expression) statement
         		if(expression) statement else statement

        Expressions are typical arithmetic, relational, conditional, expressions of C or C++ plus


        Java allows you to declare local variables and constants inside a function. You can declare a new variable or constant at any place in a function but you can not use the same identifier in different blocks. This cuase a common error with for statements like this:

         		for(int i=0; i<array.size; ++i) {...}
        You must not declare i anywhere else in the same function! This constraint makes the interpreter much simpler and possibly faster since all space for local data is allocated when the function is called rather than when it is declared.

        The following definitions define the syntax of UNIX commands and HTML related to Java.

      2. O(X)::=Optional X. #(X)::=any number of X's including none.
      3. quoted(X)::= double_quotes X double_quotes.
      4. tagged(X)::= less_than X greater_than.

      5. number::=one or more digits.


      6. CLASSPATH::UNIX_variable=Tells java tools where to to look for classes.

      7. UNIX_path::=directory #(":" directory).

      8. appletviewer::command=Scan HTML file for Applet tag and display its appearance.

      9. binary::=A file that can be loaded and run as a program which uses the machine's own language.

      10. java::command=run compiled class name (_). -- not the name of a class file!

      11. javac::command=compile Java source code file named (_) generating one or more *.class files.

      12. javadoc::command=Extract HTML documentation from Java Source code file named (_).

      13. javap::command=Disassemble a bytecode class (_).


      14. name_of_class_file::= class_name ".class". -- watch out for case sensitivity.

      15. name_of_java_file::= class_name ".java".

      16. class_name::=identifier, appearing as name of class in class definition.

      17. name_of_HTML_page::=UNIX_file_name ".html".


      18. applet_in_html::= applet_tag #(applet_parameter_tag) O(alternative_html_text) end_applet_tag.

      19. end_applet_tag::=tagged("/APPLET").

      20. applet_tag::= tagged( "APPLET" applet_tag_attributes ).

      21. applet_tag_attributes::=O(alignment) O(codebase) code width height O(alternative) O(name) O(vertical_spacing) O(horizontal_spacing).

      22. code::="CODE=" quoted(name_of_class_file), -- relative to [ code_URL ] & [ codebase ] below.

      23. width::="WIDTH=" number. -- in pixels

      24. height::="HEIGHT="number. -- in pixels

      25. alignment::= "ALIGN=" ( "LEFT" | "MIDDLE" | "RIGHT" ).

      26. codebase::= "CODEBASE=" quoted(code_URL).

      27. code_URL::=the URL of the directory that contains the applet's code.

      28. alternative::= "ALT=" quoted(text).

      29. name::="NAME=" applet_instance_name.

      30. vertical_spacing::="VSPACE=" pixels.

      31. horizontal_spacing::="HSPACE=" pixels.

      32. applet_parameter_tag::=tagged("PARAM" "NAME=" quoted(name) "VALUE="quoted(value)

      33. app_in_html::=tagged( "APP CLASS="name_of_class) ), --obsolete

      34. future_HTML::=tagged("embed" arguments) alternative tagged("/embed").

      . . . . . . . . . ( end of section Syntax) <<Contents | Index>>

      Predefined Classes

      Java is a small language that gets much of its flavor and power from the library of predefine classes. These are grouped into packages in the Java run-time library: For more see
    2. packages::= See Also see the local definitions of the
    3. hierarchy::= See
    4. classes::= See and the Official JDK 1.0.2 Documentation: [ ] , [ ] with index [ AllNames.html ] and [ ] for later versions.

      Javascript is Not Java

      Javascript is a mark up language invented by Netscape to satisfy the same need as Sun's Java. Namely to have a way of sending code across the WWW and have it run on the client's system. (Unlike a CGI [ CGI in comp.html.syntax ] which is executed on the server and sends the results to the client). It was originally called "livescript". It looks like Java. comp.lang.javascript [ ] Netscape developed a similar language to Java that is written inside HTML documents. It is not Java, but has some similar syntax and ideas.


      Specification of Java

        ISO is now involved in co-ordinating the development of a standard specification of Java. ISO has granted Sun the privilege of proposing a "fast-track" standard. For details see [ ] in Germany.

      1. ISO::="International Standards Organization".

        Microsoft would prefer its own version of Java and libraries to be used of course.

        There is a short glossary of the terms used in Java [ java.glossary.html ] in my local samples of formal documentation. "The Java Language Specification" Version 1.0 beta is at JavaSoft in compressed Postscript // and zipped postscript // Sun holds older versions (I guess). and there is a WWW version of the 1.0alpha documents [ javaspec_1.html ]

        The syntax (1.0alpha) is summarized at [ HEADING75 in javaspec_11 ] , . . . and locally [ java.syntax.html ] in my documentation samples. "The Java Language Specification" has a complete and up to date grammar. For a Lex/Yacc version of the syntax see guavac [ guavac ] at UBC. For a Java compiler-compiler see the Constructor of Useful Parsers, put out by Scott Hudson of Georgia Tech [ home.html ]

        Java has its meaning defined by a compiler into a bytecoded virtual machine, plus a specification of the virtual machine. These were once held at or I'm looking for up-to-date URLs...

        My own notes on Java semantics are under construction [ java.semantics.html ] in my documentation samples.

        (File Formats): A specification of the format of a .class file was held at [ vmspec_38.html ]

      . . . . . . . . . ( end of section Specification of Java) <<Contents | Index>>

      (JDK Specs): The Official JDK Documentation can be found at [ ] , [ ] with index [ AllNames.html ]

      See Also

        The Source Code

        Start searching here: [ ]

        News and Announcements

        [ ]

        The Java announcements archive [ ] plus my local archives of announcements: [ java.www.sites.html ] (after July 29th 1996) [ ] (before July 29th 1996)

        The Java Newbie FAQs from Usenet //

        Elliotte Rusty Harold's Official Frequently Asked Questions [ javafaq.html] .

        Also see TeamJAVA [ ] and HowDoI at Digital Focus: [ howdoi.html ] Also see Earthweb's Java Directory on [ ]

        Bugs and requested features page: [ bugsandfeatures.html ] at

        I culled a few common questions and answers in [ java.FAQ ] but these are very rough and ready as yet, and not official FAQs for Java. Also see the uneditted version: [ java.mbox ]


        (CS320 Labs): These take you step-by-step through a series of Java Applets and Programs from your first Applet to using the AWT to do graphics and layouts: [ lab1.html ] [ lab2.html ] [ lab3.html ]

        At Fairfield: [ java.html ]

        Or download, unzip, and browse thru Sun's tutorial: //

        Marty Hall's Tutorials [ #Tutorials ]


        Errata for "Java in 21 Days" [ errata.html ]

        Examples etc for "Java in a Nutshell" //

        Local information on objects in general [ objects.html ] , . . . information on language including Java [ Java in languages ] , . . . and notes and links about software engineering in general [ se.www.sites.html ]

        Finally, the pick of the Usenet news: //www/dick/samples/java.mbox

      . . . . . . . . . ( end of section See also) <<Contents | Index>>


      (CAFEBABE): On UNIX a compiled class can be recognized because it will contain the magic string of bytes that spell out in hexadecimal 0xCAFEBABE.

      The Naming of Java

      Some think it means "Just Another Vague Acronym".

      The name "Java" is not an acronym. The original name was "Oak", after the tree outside the developers window, but it turned out that "Oak" was already copyrighted/trademarked/in-use. The descriptions of the next stage vary but all indicate some kind of brainstorming session and/or a local coffee shop, during which name "Java" was proposed and accepted.

    . . . . . . . . . ( end of section The Java Programming Language) <<Contents | Index>>

Formulae and Definitions in Alphabetical Order