The Java Environment 
Peter Komisar v. 5.7  / 2008              
©              Conestoga College


Navigating the Java API

What we look at now is the HTML version of the Java
Development Kit Documentation.
A short navigation of
the documentation automatically supplies an exposure to
some
of the terminology used in the language and serves
as a brief introduction to the Java
language. Keep in mind
at this point we are not expecting
to learn the language.
We are focusing on learning how the Java documentation
is organized
to facilitate accessing the contained information
for our programming needs at this and later times.

Go to the JDK docs, on the net at:

http://java.sun.com/javase/6/docs/api/   // JDK 1.6


or on your PC. (Normally you download the documentation
and add it to the Java Home directory.) On this machine
the documentation is found at:

 file:///home/peter/jdk1.5.0_04/docs/api/index.html.


Java Packages and Descriptions

The API is really the final word on what's available to you in
Java. On opening the main page of the API there are three
frame windows.

API Frames Windows


The top left shows the packages. Clicking on any
one of these packages shows their content in the
classes window immediately below.  This reduces
the class view from all classes, to just the classes
in that package.

A set of related classes that are used together to
do work on the same area of interest are grouped
together in
packages.

For instance the 'java.sql' package has classes for
working on databases.
The 'java.net' package has
classes for networking. The lang package contains
the
fundamental parts of the language. Packages
provide a super-container for Java
classes.

Clicking the 'All Classes' link in the upper left hand
window returns the lower left view to show all the
classes in the API.


Java Classes and Descriptions

Classes are the base unit of object-oriented programming
languages.
To see the details for any particular class you
click on it's name. For now find JFrame as an
example.
What you see open in the right main frame is a description

of this class.

// Find JFrame and use it as an example


Breakdown of the Class Description Page


Summary of the Class Description Page's Content


Class Name, Relationships  & Description

At the very top of the class description page you see in
small print, the package that the class is contained in
followed
by the class name. Next is a diagram showing
where the class fits in a hierarchy in
relation to other
classes in the language.

Notice that Object class is always the top or root class
of these hierarchy trees. Interfaces
are next, followed by
the full name of the class showing
which class it extends.
( Interfaces are class-like data structures. They are a later
topic.)

// classes are part of hierarchies ultimately descending from Object

A basic description of the class is provided next. Following
this,
you may occasionally see a 'Nested' Class Summary.
( Nested or Inner Classes are
classes that are wholly defined
within another class. They too are a later subject. ) 


Fields, Constructors and Methods

The next sections shows the 'bread and butter' parts of
classes. These are the the fields, constructors and methods.
First there are fields which are data items that are defined
in the class. Also shown are 'inherited' fields. Inheritance
which we look at later is a hallmark of object-oriented
programming languages.

Next you see constructors. These are the operations that
create working copies of class definitions and load them
into memory for Java programs to utilize. Notice JFrame
has four variations of constructors listed.

// JFrame has four constructor variations

Following constructors, are the list of methods the class
supplies. The methods define what activities a class can
perform.  First a brief summary is supplied of each method.
A more detailed method description is supplied later in the
page. Again notice methods that are inherited are also listed.
Inherited methods are available for use just as methods
defined in a class are available.

Javadoc Created These Documentation Pages

These HTML pages have been built using a utility called
'javadoc' that comes with every Java distribution. Later
in this note we see that the 'javadoc' utility is used to
provide the same form of uniform documentation for
classes that you create. The same Javadoc utility has
been used by the creators of Java to create the official
documentation for the Java API.

Using 'Index'

Notice at the top of the main documentation index page
there are other hyperlinks. One is the 'Index'. The index is
handy to find a method or field by name. The link leads to
the class description in which that method was defined. To
find a method or field just click on the 'Index' hyperlink at
the top of the API index page and find the field or method
you are looking for.



Passing Command Line Arguments


Lets take care of some of the details we touched on
when we first mentioned that the main( ) method can
take arguments from the command line. We can bring
forward a HelloWorld example. We have rearranged the
presentation of the class using a popular format that
helps track curly braces and generally creates a very
readable form of Java code at the expense of brevity.
(You are free to use which ever the form that appeals
to you.)


Example  

class HelloWorld
      {
      public static void main(String [ ] args)
           {
           System.out.println("Hello World");
           }
      }

// the long but clear form


Notice the main( ) method is defined as taking 'String[]
args' inside it's round brackets. String is a Java class
that encapsulates a string of characters. While arrays
are a future topic we need to get ahead of ourselves a
bit to show how the main method's String array can be
used to pass parameters into our Java programs.

The following line will start the 'java' runtime on a Java
program called DateMaker. The words Friday and Uptown
will be passed into the program stored in the first and
second locations of the String array of main called 'args'.
The array syntax which we learn about later is at args[0]
and args[1] .  

Example

c:\> java DateMaker Friday Uptown


If you wished to supply as a parameter a String with spaces, 
then the string
is quoted as shown in  the following example.


Example 

c:\> java DateMaker "First Friday"  "Middle Uptown"

// bottom line this is how parameters are passed
// into a
Java program from the command line


Hello World With Command Line Arguments

We can adapt the HelloPlanet Program to demonstrate
how arguments can be passed in from the command line.
To demonstrate we need to ignore the fact that we haven't
looked at Java arrays or control logic yet. The focus here
is on getting parameters from the command line into the
program.

The program will print a prompt if you haven't entered
anything and one word if you do. The program will treat a
group of words as one word if you put them inside double
or single quotes. If not quoted, the next string becomes
the next arg of the array and is ignored in this example.

Example

class Hello{
  public static void main(String [] args) {
     if(args.length < 1)
     System.out.println
     ("Run Hello with your name typed after Hello!" );
     else
     System.out.println("Hello "  + args[0] +"!"  );
     }
  }

This is not the handiest way to communicate to a Java
program. There are more flexible
ways for interacting with
a program from the command line. As well visual GUIs
can be
used to enter information to a program. This
technique has it's place though, mainly for passing

configuration parameters that will be valid for the entire
time that a program is running. An example
of what might
be suitable for passing in from the command line might
be a location and a time zone for a weather program.



Unicode & Character Sets


The character set that Java uses to read and write is
called Unicode. Java can converse in the ~35,000 world
characters that Unicode supports. These character sets
include about 20,000 pictograms that are used by the Han
dialects which are used in the Chinese, Japanese and
Korean languages.

The symbols we use to communicate, whether in a spoken
or computer language, have been grouped into well known,
character sets which have become world standards.

Initially computers used the 128 characters of ASCII. Later
the extra bit of each byte that wasn't being used in ASCII
was used to describe another 128 characters to create the
character set ISO-8859-1. Unicode is a practical compromise
between these first
small character sets and the mammoth
UCS-4 that has room for every dialect that has
ever existed
or is likely ever be found or invented.

Unicode is the first 65,536 characters of UCS-4, what they
call the 'first plane'. ( USC-2 is a two-byte standard that is
the same as Unicode.) USC-4 is an internationally endorsed
ISO/IEC
standard that is also referred to as ISO/IEC 10646.

Unicode uses two bytes to describe each character. Each
character has a representation in the
Java language as a
'char' primitive type. To assign a 'char' type (as a char
literal) single quotes
are used.

Example     

char letter= 'A';

How do you represent the letters beyond what can be
generated on your QWERTY keyboard?
To represent the
rest of the Unicode letters the Unicode escape sequence
is used.
This escape has the form, \ uhhh where each h
represent a hexadecimal number.
FFFF, for instance, is
hexadecimal for 65,536. Notice also the escape sequence
is included
within the single quotes for the char type.

Example

char exotic='\uAB9F';

// notice you might quickly load this into a program and run it and be
// disappointed
to see a square box or question mark instead of some
// letter. There are two key issues here. First many
of the character
// positions haven't been assigned. Second, the underlying operating
// system must
be set to support Unicode.
 

Unicode Escape Example

class Unicode{
    public static void main(String [] args) {
     System.out.println("The Letter Before B: " + 'A' );
     System.out.println("Escaped Unicode Character: "  + '\uAB9F' );
     }
  }

 
Switching between hexadecimal and decimal

If you are running windows you can go to Start ->Programs ->Accessories->Calculator. Switch the view to scientific.
Click on hexadecimal. Enter FFFF. Click on decimal
and
it will show the equivalent value in decimal. In reverse,
enter the number 65,536
in decimal mode, click
Hexadecimal and you will see FFFF generated. If you
are
running Linux, there is a calculator in Linux distros
as well.


Character set organization evolved in a natural progression
where each successively larger character set became a

superset of it's predecessor. As a result a letter represented
in the first 7 bits of a Unicode
character will be an ASCII
character. If a character is stored in the first 8 bits of a
Unicode
character it will be an ISO-8859-1 character.
 

Containment Hierarchy of the World Character Sets
 
 UCS-4 aka ISO/IEC 10646 
 // uses 4 bytes with a range  of over 4 billion characters   
 Unicode aka UCS-2 
// uses two bytes to code 65536 characters
 
    ISO-8859-1 
 // uses all 8 bits of a byte to create 256 characters
 
  ASCII
// 7 bits of one byte, 128 characters

//  ASCII is a subset of ISO 8859-1 is a subset of Unicode/(UCS-2)
// is a subset of UCS-4/(ISO/IEC 10646)

 

Summary of Primary Features of World Character Sets
 
 ASCII   American Standard Code for 
 Information Interchange
 7-bits, 
 [one byte]
 128 characters mostly 
 humanly readable
 ISO 8859-1  256 ISO character code   8-bits,
 [one byte]
 includes many non-
 English characters
 Unicode  synonymous with UCS-2  16 bits, 
 [two bytes] 
 most of the world's 
 characters 
 UCS-2   Universal Character Set
 two byte encoding
 16 bits, 
 [two bytes]
 1st plane of ISO/IEC 10646 
  in two bytes (0 to 64K)
 USC-4  Universal Character Set
 four byte encoding
 32 bits, 
 [four bytes]
 Full ISO/IEC implementation
 in 4 bytes
 UTF-8 *  UCS Transformation Format
 versatile but complex
 [1 to 
  4 bytes]
 if bit 1 is 0,-->1 byte ASCII
 if 1st bits are 110,-->2 bytes
 if 1st bits are1110,->3 bytes etc.
 UTF-16   extended variant of UCS-2  [2 to 4 bytes]  
 binary  data transfer in numeric form  [1 to 8 bytes]  for java chars, binary is Unicode
 objects    streaming java objects         [variable length]   the serialization  process 


UTF Universal Character Set Transformation Format

As you can imagine, if you were conveying a lot of ASCII
character data over a
telephone line, you wouldn't want to
be using two or four bytes where one would do.
UTF is a
transformation format that can use a variable number of
bytes to describe
letters. If it is being used to convey ASCII
letters UTF-8 will only use one byte to send
the character.

If the letter is a Unicode character more bytes will be used.
Up to 4 bytes
are used in this system. UTD-16 uses 2 to 4
bytes variably. The reason it is mentioned
here, other than
to complete the topic is Java has methods that will support
transmitting
information using UTF formats.

Practically Speaking

Speaking practically, Java can be thought of as supporting
UTF-8 and Unicode 'out of the box'. Unicode automatically
supports the many smaller subordinate character sets such
as ASCII and ISO-8859-1.

   UTF-8 Notes      // for reference

  
Following is an interesting note, regarding UTF-8. It was
invented by Ken Thompson, the inventor of Unix.

// Quoted from "UTF-8, a transformation format of
ISO 10646,
// http://www.ietf.org/rfc/rfc3629.txt


"UTF-8 was devised in September 1992 by Ken Thompson,
guided by design
criteria specified by Rob Pike, with the
objective of defining a UCS
transformation format usable in
the Plan9 operating system in a non-
disruptive manner.
Thompson's design was stewarded through
standardization
by the X/Open Joint Internationalization Group. __
"

"The table below summarizes the format of these different
octet types.
The letter x indicates bits available for
encoding bits of the
character number."

Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
.

The following site will show you the various character
sets that Java supports through Unicode and why putting
all these encodings into manageable sets was needed.

http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html


Identifiers, Escape Sequences & Comments


Identifiers

Names are needed to identify the different elements a
developer creates in a Java program. Again the 'HelloWorld'
program is useful to examine identifiers. The identifier of the
class is HelloPlanet. So the name 'main' identifies the main( )
method. Each of the names used in the System.out.println
statement are identifiers as is the the args word in the brackets
of main. Other words in the code, like the words class, public,
static and void are special reserved words used by Java. The
set of reserved words in a programming language are called
it's 'keywords'.

Example       

class HelloPlanet{
  public static void main(String [ ] args) {
  System.out.println("Hello Planet");
  }
}

// Java identifiers in blue, Java identifiers that are reserved,
// keywords in red

Properties of Java Identifiers

Java is a case sensitive language. The identifier 'dog' and 'dOg'
are unique identifiers in Java. Java identifiers cannot be keywords.
Only certain characters can be used in identifiers. The rule goes
as follows.

An identifier can start with a letter, underscore or a dollar sign.
Subsequent characters can be any of these and may also be
number characters.

To summarize Java identifiers are the following.

Java Identifiers Properties


Examples

1. $9 is a legal identifier

2. %bob is not as % is not a letter, underscore or dollar sign.

3. _33$ is legal identifier (even if you wouldn't want to use it)


4. $__Bill is also a legal identifier.


5. 7row is not legal as Java identifiers cannot start with a number.

There are a few things to note at this time. Identifier
characters can be any character that is defined as being
a letter in the Unicode character set. This feature allows
Java programs to be created using identifiers that are
written in the various languages of the world.

Identifiers Cannot Be Forward Referenced

Another point, Java will not allow you to forward reference
or use a name before it has been defined. 

// letters may include Unicode letters
// variable names cannot be forward referenced.


The Terms 'Scope' & 'Namespace'

When we name a class we created a bounded region
called a 'scope'. This area may be thought of as a
'namespace' associated with the name of the class.

In the following example 'class scope' is the area between
the curly braces

Example

class Scope
    {
    // the area between the braces
    }

Escape Sequences

We saw we could use an escape sequence to specify a
Unicode letter. Escapes are used for other symbols as
well. In quotes the escaped character is prefixed by a
single backslash. In char literal assignments the escaped
characters are enclosed in single quotes.

Java Escape Sequences
 
 In a String   In char assignment  character escaped
 \uhhhh   '\uhhhh'  Unicode character
  \'    ' \' '   single quote
  \"   ' \"'  double quote
  \n    '\n'   newline
  \r    '\r'   return
  \t    '\t'   tab
  \b   ' \b'   backspace
  \f   '\f'  formfeed
 \\   '\\'  backslash


Example

class Escapes{
  public static void main(String[ ]args){
     char[ ] escapes=new char[9];
     String[] names={ "Unicode","double quote",
                           "single quote","newline",
                           "return","tab","backspace",
                           "formfeed", "backslash"};

        escapes[0]='\u0050';
        escapes[1]='\'';
        escapes[2]='\"';
        escapes[3]='\n';
        escapes[4]='\r';
        escapes[5]='\t';
        escapes[6]='\b';
        escapes[7]='\f';
        escapes[8]='\\';

    for(int i=0;i<escapes.length;i++){
       System.out.println(names[i] +" escape: " + escapes[i]);
       }
       // notice formfeed and newline are
       // exercising their effect in the output!
       
       System.out.println("\n\n Escapes \n In \n A \n String" +
                          "\n Don't \n Need \n Quotes");  
    }    
 }


// this code uses arrays which we cover in detail later
// not to worry about them at this point.


Comments

Java gives you three options for including comments
in your source code. Comments are used to document
programming code but have no effect on what the code
does when it is run. The first style is inherited from C++.
Two forward slashes will comment out everything in a line.
The comments only apply to a single line. A separate
pair of forward slashes must be provided for each line
that needs to be commented out.

Example   

//  comments out to the end of this line


The second style is older still and comes from the 'C'
programming language. The 'forward
slash asterisk
asterisk forward slash' comment,  /*      */  is useful
for commenting out a long
statement or section of code.


Example
  

/ *  start of a very long comment
     which may extend over several
     lines. 
                                    */


The javadoc Utility

A third comment style is unique to Java. Peter Van der
Linden in 'Just Java' relates that the 'javadoc' utility is
an example of an 'automatic document generator',
invented by Donald Knuth. It looks like the   /*   */  
comment form taken from 'C' however a second
asterisk is added immediately following the first one,
/**   */.  Following are examples that include various
javadoc variables.

The @ symbol prefixes pre-defined document terms
which loaded by following them with appropriate input
values.


/** My Hello Program
    Building on the notion of Greeting
    @version 9.49382
    @author Pee Kay Jay
    @see Hi class
    <i><b>ITALIC BOLD HELLO!</b></i>
 */

// before the class

/** The main method is where the program begins
    
     @param - main takes a String array
     @return - main returns void       
     @exception  - main does not throw an exception explicitly!

*/

// before main( )

For reference, the following table is supplied which shows
all the javadoc tags that have been introduced up to version
5 of the JDK.

Javadoc Tags & Version in which they were introduced 

// table from the JDK1.5 documentation

Tag Introduced in JDK/SDK
@author 1.0
{@code} 1.5
{@docRoot} 1.3
@deprecated 1.0
@exception 1.0
{@inheritDoc} 1.4
{@link} 1.2
{@linkplain} 1.4
{@literal} 1.5
@param 1.0
@return 1.0
@see 1.0
@serial 1.2
@serialData 1.2
@serialField 1.2
@since 1.1
@throws 1.2
{@value} 1.4
@version 1.0


If the 'javadoc' utility is run against a source file containing
Java classes, a whole set of interconnected HTML files will
be generated showing Javadoc style documentation. The
following example shows that the author and version flags
have to be included for the version and author tags to show
up in the documentation.

Example  

c:\> javadoc -version -author Hello.java


If you run 'javadoc' at the command line without arguments
you will see a summary of options and flags that can be set.


Example
    c:\> javadoc   // enter without additional arguments


Note javadoc style comments cannot be located inside a method.



Using and Creating Packages


We have seen from the Java library all the classes that
are of like purpose
are organized in larger units called
'packages'.  These packages are also
available to us to
organize the classes we create. Up this point the only
code
we have seen is HelloWorld and we have created
a variation of it in
HelloPlanets.

What is not evident is that HelloWorld is in an invisible
package which 'javac'
compiler has supplied for us called
the 'default' package. The default package
is unnamed
and corresponds to the current directory. If we wanted to
put class
in a larger package we would put a package
statement at the head of our source
file.


Example
    

package hellos;



By convention, package names are lower case.


Later we will see we can make package classes
available for our use via import
statements as is
shown in the following example.



Example
     

import hellos.*;  

// wild card, *  imports all classes in hellos package



Fully Qualified Names

When we did HelloWorld we were in an anonymous
'default' package. If HelloWorld was in a 'hw' package
we might refer to it by it's fully qualified name which
includes it's package.


Example


hw.HelloWorld

// fully qualified class name for HelloWorld class inside hw package



To show an example of an import of a common Java
API package, we can
show the import of the 'java.awt'
package. This was the original set of GUI
components
that came with the first editions of Java. It contains
many classes
that are important to building GUIs or
Graphical User Interfaces.



Example
 


import java.awt.*;


This will make all the classes in the java awt package
available to us. We could
for instance reference the
Frame class via it's short name, rather than it's 'fully
qualified' name.

Example
 

Frame frame;

If we didn't have the above import we could instead
use the class fully qualified name.

Example

java.awt.Frame frame;   


// using the 'fully qualified' name of this class 
// without importing the package


Notice that imports are not 'recursive' and will not import
the classes of nested packages that a package may
contain.
If we looked back at the API index we would find
in the library, the 'java.awt.event' package resides in the
java.awt package. This package requires it's
own import
should you need it's classes.

a

Example
    


import java.awt.*;
import java.awt.event.*; // importing a nested package



HelloWorld in a Package


Consider an expanded version of HelloWorld, a sort of
HelloWorlds collection where
alien invaders wish to say
'Hello' to several planets of our solar system. In the next

example we put three 'HelloWorld like' classes into a
package  called 'alienHi'. We
include a class called
'HelloPlanets' that has a main method that is used to
create 'new'
instances of these classes. We will talk
about what 'new instances' means later. For
now we can
think of them as executions of the code associated with
each class.


The key line that does this is the following.


Example
    

package alienHi;



PIC
// package, imports, classes

Notice that the package declaration is the first line of
code in the source file. We can
using the memory aid
'PIC' to remember that the order in which items in a
source
file must appear is Packages, Imports then
Classes.



// long code sample but not complex,
three similar classes and a runner class.


package alienHi;
 
// imports
   
class Mercury
      {
      // the constructor calls helloMercury() method
      Mercury()
        {
        helloMercury();
        }
      // a method to greet Mercury
        void helloMercury()
       { System.out.println("Hello Mercury!");
       }
       }
     
    // The Venus class sends a Greeting to Console
class Venus
      {
      // the constructor calls helloVenus() method
        Venus()
        {
        helloVenus();
        }
      // a method to greet Venus
        void helloVenus()
       {
       System.out.println("Hello Venus!");
       }
      }
       // The Earth class sends a Greeting to Console
class Earth
      {
      Earth()
        {
        helloEarth();
        }
      // a method to greet Earth
        void helloEarth()
       {
       System.out.println("Hello Earth!");
       }
    }
   
     // HelloPlanets is a runner class in which we instantiate
     // classes that say 'Hello' to different  planets. 

     public class HelloPlanets
        {
       public static void main(String[]args)
        {
         new Mercury();
         new Venus();
         new Earth();
        }
       // method called by TagAlong
        public void
helloVenus( ){
                System.out.println("HelloPlanet's own helloVenus method");
                }
   
      }  



Reminder of Steps to compiling and running a Java program


1. Generate source code in an ASCII editor
2. Name the file identically to the class name + the .java extension
3. Open a Dos/Unix window and type javac followed by the file name,
    (Name.java) and press enter // compiles
4. If the compilation was successful the Dos prompt returns, then type java
    followed by the class name with no extensions // interprets


Paralleled Package & Directory Structure

In the above example, an 'alienHi' package contains the
three classes and the class containing the main( ) method.
In practice, we need to create a parallel directory structure
that maps to the package structure.  We can use the 'md'
or mkdir commands at the command line or use a Windowing
GUI to create this directory structure.

In our case we need one directory called 'alienHi' in
which we locate the classes, Mercury, Venus, Earth
and HelloPlanets.

Example of Directory Structure that Parallels Package Structure

alienHi // directory
     |__ Mercury  // classes
     |__ Venus
     |__ Earth

The structure is really only significant to the compiled Java
code. Once this directory is created the corresponding
source code can be moved to a source directory. Assuming
you have the source file in the alienHi directory, one might
compile as follows.


Example
c:\> javac HelloPlanets.java

 // alternatively you could cd up directory and compile as follows.

c:\> javac alienHi \ HelloPlanets.java    // spaces added for readability!

// this works too


Running though, if you tried the following it doesn't work.

Example

c:\>  java    alienHi \ HelloPlanets  // syntax doesn't work


This is because class files follow a different path system.
Once a class has been put into an explicit package, to run
it using the 'java' interpreter, the class needs to referenced
via it's fully qualified name using 'dot' notation.  Put yourself
at the same directory level as the package directory, then
run the command as follows.

Example 

c:\> java alien.HelloPlanets  // runs

Using import Statements

In order to make classes in another package available
to a class, the classes can be referenced by their fully
qualified name or by using their local names after
importing the package they are in.


Example

import alienHi.*;   
// could have used ' import alienHi.HelloPlanets; '


class TagAlong{

public static void main(String []args){
 HelloPlanets hp =  new HelloPlanets( );
 hp.helloVenus( );
  }
  }


// alienHi needs to be in the same directory
// as the class TagAlong or you need to set
// the path environmental variable

For a single class we might have used the fully
qualified name and avoided using the import.


Example


class TagAlong{

public static void main(String []args){
 alienHi.HelloPlanets hp =  new alienHi.HelloPlanets( );
 hp.helloVenus( );
  }
  } 



Top Level Classes

If you asked why not compile to the name of one of the
the classes, say Mercury or Venus we run into a compiler
error. This is because in Java there is a rule that states
that there can be only one 'top-level' class in a source file.

Only one class can be marked public in a source file and
that class must be the top-level class. Typically, all the
classes in a source file will be related and run in the
context of one main( ) method. The main( )  method,
then is usually put in the 'top level' class marked public
from where the program is run. You can think of the
other classes as 'helper' classes.


Top Level Classes

// each class may have a main method but usually this wouldn't be useful

The whole idea of describing 'top level' classes is important
when more than one class is defined in a single text file. This
might be useful if the classes are highly co-dependent.

Alternatively, it is more modular to keep each class in it's
own source file.


Self Test                                                                  Self Test With Answers


1) In the following which is arg[0]  // assume main has arguments ( String [] arg )

c:|> java Movie Terminator X-Men Hulk Batman 

a) java
b) Movie
c) Terminator
d) X-Men
e) Hulk
f) Batman

2)  Java identifiers are case sensitive .  ___


3) The class file created by the javac compiler will have the same
name as the top level class in the corresponding source file. 
                                                                    [ True  or  False ]

4) The following are valid identifiers [True or False]

f) $999
g)  %box
h) J-Tree
i) _$_$_9
j) Walter&89

5) The following are valid comments [Mark each True or False ]

a)  /** last comment **/
b)  //another comment */
c)  /** and another
d)  // comment falls through
        to next line
e) /*    /Hello/       */

6 ) The following are valid escape sequences. [ Mark each True or False]

a)   \\
b)   \b
c )  \n
d)   \x

 7 ) Importing a Java package using the asterisk 'wild card' will make
available all the classes in the package, as well as classes in other
packages nested inside this package. [True or False ]


8 ) A source file with a number of classes will only have one class
     that is both marked public and contains a main( )  method. [True or False ]

9 ) Based on information in this note and looking at the HelloWorld code,
    Indicate the order that the following keywords will first appear in a
    correct Java source code file.

   a ) class _____
   b) public _____
   c) 'import  ____
   d) package _____



Exercise

1) Using the earlier Planets class, put the class in the 'solar' package.
by adding the line 'package solar; to the head of the source file.

Create the needed parallel directory system on the computer.
i.e. The compiled class will need to reside in the solar directory.
When you compile, from above this directory the command line
will be something like

javac solar\Planets.java   // windows command line

To run however, we will need to address the package  the classpath.
Therefore to run the following syntax is required.

java solar.Planets

Try it to get use to working with Java classes inside packages.

Do a screen shot or just copy and paste the command line execution
of the class along with the output it supplies.

2)  List three legal identifiers all which have numbers in their bodies,
     each starting with one of the three legal starting characters.

     a )       

    b )  

    c )

3) What would be the correct statement to import any of the classes
in the java.net package. Note statements always end in a semi-colon.

4) What would be the correct statement to put at the head of a source
   code file that would put the subsequent class code into the 'rocket'
   package.

5) If a top-level class in the rocket package is called 'Booster' what
would the command line be to run the class file.

6) Cut and paste the HelloPlanets source code into an editor. Change
the comments to Javadoc style comments. Run the source code at
the command line. Note you will need to put HelloPlanets in it's own
alienHi directory. Also, in order for the helper classes,  Mercury, Venus
and Earth, to be documented by Javadoc, you will need to use the
--package flag. Following is what the command will look like at a Linux
console, the only difference from Windows being the forward slash
separating the directory and file name, 'alienHi and HelloPlanets.java'.

[peter@localhost Examples]$ javadoc -package alienHi/HelloPlanets.java

If you browse the directory and open on the index.html page you will
see the Javadoc documentation generated for the classes.

Do a screen shot or just make a copy of the index.html page and add
it to the assignment you hand in.


  Supplemental:  Java Resources


1) Please feel free to join Sun's Developer Connection.
It is a free and completely benign registration process.
( In over 10 years since registering  I have never been
contacted or received any pesky e-mail related to
registering.)  You do not need to join. The download may
be available without registering.

2) If you haven't already done so while reading the page on
resources, make sure you browse 'Training' at the Developer
Connection. This remains one of the best places to get top
quality, first hand Java information especially for newly
released APIs.    http://developer.java.sun.com/developer/
 

3) You may wish to take a look at some of the lightweight
editors that are available. If you are using Windows you can
use Notepad, WordPad or even Edit or you may wish to try
the free editors JCreator, TextPad or JEdit. 

// JEdit has a strong developer community behind it and
// can be used with a multitude of languages

If you are running in a Unix or Linux environment any text editor
that you like will do.  (Kwrite auto-colors and does brace matching.)

On a rare occasion an editor can introduce a bug if doing automated
compile and running. If you are suspicious you have a bug that you
didn't write, you can always use the editor just to prepare and save
your code and compile and run the code from the command line.

// really this is recommended when learning so you are strong
// at the command line after the course. Use the editor with
// color coding for writing and saving but compile and run at
// the command line.

4) The Eclipse editor that was opened sourced by IBM is a
great sophisticated editor that you can use if you are use to
using IDEs. Also Netbeans comes with the Sun JDK download
so it is also very convenient.  (These have 'learning curves' in
their own right so don't let them be a distraction  from learning
fundamentals! )

// You can use these as simple editors though they are
// complex programs

If you are an ultra-conservative Windows user and prefer to use
the old  DOS editor Edit, keep the program open and start up a
second DOS window to compile and save your code. This will
speed your development process.