Java Language Notes




Keywords

abstract    boolean      break       byte        case      catch          char
class       const        continue    default     do        double         else
extends     false        final       finally     float     for            goto
if          implements   import      instanceof  int       interface      long
native      new          null        package     private   protected      public
return      short        static      super       switch    synchronized   this
throw       throws       transient   true        try       void           volatile
while








Primitive Variables

  • Ranges:
  •                     Integers
                 Bits             Range
                 ----    -------------------------
      byte         8            -128 <> 127
      short       16          -32768 <> 32767
      int         32     -2147483648 <> 2147483647
      long        64       -9.2 e-18 <> 9.2 e18
    
    
                         Floats
                 Bits             Range
                 ----    -------------------------
      float       32        1.4 e-45 <> 3.4 e+38
      double      64       4.9 e-324 <> 1.7 e+308
    
    
    
  • Wrapper Classes: The Integer, Float, and Character Classes are object wrappers for the primitives and provide .MIN_VALUE and .MAX_VALUE constants. For the float they also provide: .POSITIVE_INFINITY, .NEGATIVE_INFINITY, and NaN (Not A Number).
  • Exceptions: Integer operations will throw a ArithmeticException exception on a division by zero. Float operations do not return exceptions but return .POSITIVE_INFINITY, .NEGATIVE_INFINITY, and NaN. No exceptions are thrown for overflow or underflow errors.
  • Arithmetic Operations: All integer operations are done at a 32 bit width (shorter types are promoted to 32 bit for the calculation) unless one of the operands is 64 bit in which case the operation is done in 64 bits. When opretions involve integers and floats, all operands are converted to 32 bit floats. If a double float is involved then the calculation is done in 64 bits.
  • Assignments: When assigning integer variables of either integer or float a cast is only required when squeezing a type with more bits into a smaller type. For example int -> byte, or double -> float. Casts are also required when assigning a integers to floats and vice versa. Floats are truncated when cast to integers.
  • Literals: Integer literals like "1234" default to type int unless folowed by a "L" denoting them as long ( "1234L"). Float literals require a decimal point or exponent to identify them as floats. They default to long unless followed by a "F" (for float). Examples: 1.0, and 1.0E23
  • Boolean: Booleans are either equal to true of false.
  • Character: The char type contains a 16 bit Unicode character (\u0000 to \uffff)

  • Compiling and running Java applications from the Command Line

    To compile and run a Java application program, that accepts command line parameters, from a command line (Using Suns JDK on Dos or Unix):
    Create a file called AJavaApp.java that contains:
    public class AJavaApp
     {
      public static void main( String Args[])
       {
         AJavaApp ja = new AJavaApp();
         ja.doIt(Args);
        }
    
      public void doIt( String [] inArguments)
      {
       for (int i=0; i < inArguments.length; i++)
        {
         System.out.println("Command Line Argument # " + Integer.toString(i) +
          " = " + inArguments[i]);
        }
      }
    
    Compile these files using the Sun javac command like so:
      javac AJavaApp.java
    Then run the program by entering:
      java AJavaApp aaa bbb ccc
    It should then print out each of the command line parameters you entered. 

    Arrays

  • Running through elements in an Array
  • Copy Array
  • Passing Arrays between Methods
  • Catching Bad Array index
  • Multi-dimensional Arrays
  • Array of Objects
  • Running through elements in an Array

       int [] numbers = { 1, 2, 3, 4, 5 };
    
       //*** Print out elements of Array
       System.out.print("Printing array: ");
       System.out.println();
    
    Output = Printing array: 1, 2, 3, 4, 5,
    
    

    Copy Array

       //***** Create a new array twice the size of the original, and copy the original
       //***** into the new array then- set the original array name "numbers" to the new array
       int [] numbers = { 1, 2, 3, 4, 5 };                               //Original Array
       int [] copyOfNumbers = new int [numbers.length * 2];              //Copy to Array
       System.arraycopy( numbers, 0, copyOfNumbers, 0, numbers.length);  //Do array copy
       numbers = copyOfPrimes;               // Set "numbers" to point at new array
    
    
    

    Passing Arrays between Methods

    public void runTests()
      {
       int [] numbers = { 1, 2, 3, 4, 5 };
    
       // Call another method passing it the array
       char [] lettersReturned = PassArray(numbers);
    
       for (int i=0; i < numbers.length; i++)
        {
         System.out.print( numbers[i] + ", ");
        }
       for (int i=0; i < lettersReturned.length; i++)
        {
         System.out.print( lettersReturned[i] + ", ");
        }
       System.out.println();
      }
    
     public char [] PassArray(int [] inArray)
      {
       char [] letters = { 'a', 'b', 'c' };
    
       // "inArray" points at original array in arrayTest
       System.out.print("Passing array to method: ");
       for (int i=0; i < inArray.length; i++)
        {
         inArray[i] = 9;                        //* Change array in calling method
        }
        return letters;
      }
     
    
    Output = Passing array to method: 9, 9, 9, 9, 9, a, b, c,
    
    

    Catching Bad Array index

        String [] s = { "one", "two", "three" };
    
        try {
        for ( int i = 0; i < 999; i++)
         {
           System.out.print( s[i] + ", " );
         }
            }
         catch ( ArrayIndexOutOfBoundsException err)
            { System.out.println("Handled error: " + err.getMessage() ); }
        System.out.println();
    
    Output = one, two, three, Handled error: null
    
    

    Multi-dimensional Arrays

       char [][] myMatrix = {
          { 'x' },
          { 'x', 'x' },
          { 'x', 'x', 'x' },
          { 'x', 'x', 'x', 'x' },
          { 'x', 'x', 'x', 'x', 'x' },
          { 'x', 'x', 'x', 'x' },
          { 'x', 'x', 'x', },
          { 'x', 'x' },
          { 'x', }
        };
    
       System.out.println("Multi Dimension Array Test: ");
       for (int i = 0; i < myMatrix.length; i++)
        {
         for (int k = 0; k < myMatrix[i].length; k++)
          {
           System.out.print( myMatrix[i][k] );
          }
         System.out.print("\n");
        }
       System.out.println();
    
    Output =
    x
    xx
    xxx
    xxxx
    xxxxx
    xxxx
    xxx
    xx
    x
    
    
    

    Array of Objects

    class rec
    {
      public int i;
      public String s;
      rec(int iIn, String sIn)
       {
        this.i = iIn;
        this.s = sIn;
       }
    }
     .........................................
       Character charObj;
       Object [] objArray = new Object[10];
    
       for (int i = 0; i < objArray.length; i++ )
        {
         charObj = new Character( (char)(i + 97) );
         objArray[i] = new rec( i, charObj.toString() );
        }
       for (int i = 0; i < objArray.length; i++ )
        {
         System.out.print( ((rec)objArray[i]).i + " " + ((rec)objArray[i]).s + ", " );
        }
       System.out.println();
    
    Output = 0 a, 1 b, 2 c, 3 d, 4 e, 5 f, 6 g, 7 h, 8 i, 9 j,
    
    
    
    
    
    
    

    Vectors

    import java.util.Vector;
    import java.util.Enumeration;
    
    //************************************************************************
    //***************** Test Programs ****************************************
    //************************************************************************
    class TestPrograms
    {
     // Vector Notes:
     // Vectors are dynamic arrays of Objects that grow automatically as needed.
     // Vectors Capacity is how many elements they can currently hold before growing.  They
     // default to growing by *2 unless its specified with a 2nd parameter (capacity increment)
     // Vector Constructors:
     //  Vector StringVector = new Vector();    //Constructor:defaults to capacity size of 10
     //  Vector StringVector = new Vector(1);   //Constructor: set to capacity size of 1
     //  Vector StringVector = new Vector(1,2); //Constructor:Capacity=1, Capacity increment=2
    
     Vector StringVector = new Vector(1);
    
     public void doSomething()
     {
      StringVector.addElement("one");
      printVector();                     //Output = "Vector=one,"
      StringVector.addElement("two");
      printVector();                     //Output = "Vector=one, two,"
      StringVector.addElement("three");  //Output = "Vector=one, two, three,"
      printVector();
    
      StringVector.setElementAt("TWO", 1);
      printVector();                         //Output = "Vector=one, TWO, three,"
      StringVector.removeElement("TWO");
      printVector();                         //Output = "Vector=one, three,"
      StringVector.insertElementAt("two", 1);
      printVector();                         //Output = "Vector=one, two, three,"
    
      System.out.println("First Element = " + StringVector.firstElement()
                         + " Last Element = " + StringVector.lastElement() );
      //Output = "First Element = one Last Element = three"
      if ( StringVector.contains("two") ) System.out.println("Vector contains \"two\" ");
      //Output = "Vector contains "two""
      if ( !StringVector.isEmpty() ) System.out.println("Vector is not emptey");
      //Output = "Vector is not emptey"
      System.out.println("Index of \"two\"  is " + StringVector.indexOf("two") );
      //Output = "Index of "two"  is 1"
    
      printVector();                     //Output = "Vector=one, two, three,"
      StringVector.removeElementAt(0);
      printVector();                     //Output = "Vector=two, three,"
      StringVector.removeElementAt(0);
      printVector();                     //Output = "Vector=three,
      StringVector.removeElementAt(0);
      printVector();                     //Output = "Vector="
      if ( StringVector.isEmpty() ) System.out.println("Vector is emptey");
                                         //Output = "Vector is emptey"
     }
    
     public void printVector()
      {
       Enumeration enum = StringVector.elements();
    
       System.out.print("Vector=");
    
       while ( enum.hasMoreElements() )
        {
         System.out.print( enum.nextElement() + ", " );
        }
       //This could also be written as follows:
       //for (int i =0; i < StringVector.size(); i++)
       // { System.out.print( StringVector.elementAt(i) + ", " ); }
       System.out.println();
      }
    
    
     // Other Vector Methods:
     // .trimToSize()  Trim off unused capacity from Vector to save memory
     // .size()        Return current elements in use
     // .capacity()    Return current capacity of Vector
    
    }// ******************** End of TestPrograms Class *************************
    
    
    
    Output =
    Vector=one,
    Vector=one, two,
    Vector=one, two, three,
    Vector=one, TWO, three,
    Vector=one, three,
    Vector=one, two, three,
    First Element = one Last Element = three
    Vector contains "two"
    Vector is not emptey
    Index of "two"  is 1
    Vector=one, two, three,
    Vector=two, three,
    Vector=three,
    Vector=
    Vector is emptey
    
    

    javadoc

  • Javadoc Tags
  • @version 1.0, DD MMM  YYYY"
    @author  John Donohue
    @param "variable name" "description of parameter".
    @return "description of returned variable".
    @exception "exception name" "description of exception".
    @see "class name" # "field, method or constructor name"
      Examples:  (These examples are from Sun's Doc)
       @see String#equals
       @see java.lang.String
       @see String
       @see java.lang.Object#wait(int)
       @see Character#MAX_RADIX
       @see <a href="spec.html">Java Spec</a>
    
    OR
    
     * @javaDocTemplate.java
     * @version     1.0, 07 Apr 1997
     * @author: John Donohue
     */
    public class javaDocTemplate
     {
       /**
        * instance variable.
        * @see java.lang.String
        * @see javaDocTemplate#exampleMethod
        */
       public String theAnswer;
    
       /**
        * Example of method documentation.
        * @param p1 is parameter number one.
        * @param p2 is parameter number two.
        * @param p3 is parameter number three.
        * @return the value returned from this function.
        * @exception e1 an exception thrown by this method.
        */
       public String exampleMethod(int p1, int p2, int p3)
       {
        throw e1;
        returns theAnswer;
       }
     }
    
    

    Using "break" to leave a control block

  • Using the break statement to exit a control block (instead of goto)
  • class tst
    {
      public static void main( String args[])
       {
        boolean eatsMeat = true;
        boolean eatsPlants = true;
    
        describeIt:
        {
         if ( (eatsMeat == true) && (eatsPlants == true) )
          {
           System.out.println("Its an Omnivore");
           //If its a Omnivore we dont want to overwrite it with "Herbivore", or "Canivore"
           break describeIt;
          }
         if ( eatsMeat == true )
          {
           System.out.println("Its a Carnivore");
          }
         if ( eatsPlants == true )
          {
           System.out.println("Its a Herbivore ");
          }
        }
    
       }
    }
    
    

    Converting between data types.

    //int to String
    int i;
    String s = Integer.toString(i);
     or
    String s = new String("" + i);
    //String to int;
    int n = Integer.parseInt("1234");
    //String to long;
    int n = Long.parseLong("1234");
    //String to float, Note: Requres JDK 1.2
    int n = Float.parseFloat("1234");
    
    

    The try, catch and finally control blocks

  • Using the try, catch and finally control blocks to catch exceptions
  • class tst
    {
    
     public static void main( String args[])
      {
        int [] iArray = new int[10];
    
        try
         {
           System.out.println("In try control block");
           iArray[99] = 1;
         }
        catch ( ArrayIndexOutOfBoundsException err)
         {
          System.out.println("Handled error: " + err.getMessage() );
         }
        finally
         {
           System.out.print("The \"finally\" control block is always executed following the");
           System.out.println(" \"try\" control block wheter or not their is an exception");
         }
    
      }
    
    }
    
    

    Hastables

  • Using Hashtables to store name/value pairs.
  • import java.util.*;
    
    class tst
    {
    
     public static void main( String args[])
     {
       Hashtable h = new Hashtable( 3, 0.5f); //Parameters are Intial size, and Load Factor
       // Use "put" to add a key/value pair to the Hashtable
       h.put("peter","parker");    // peter is the key parker is the element
       h.put("clark","kent");      // clark is the key, kent is the element
       h.put("tony","stark");      // tony is the key, stark is the element
       // the value can be any Object including String
    
       // Use "get" to retrieve a value of a particualr key.
       String s = (String)h.get("peter");
       System.out.println("peter = " + s);
    
       // using Enumeration to print all elements in the Hastable
       Enumeration e = h.elements();
       System.out.println("Printing out all Elements in Hashtable");
       while (e.hasMoreElements())
        {
         System.out.println( e.nextElement());
        }
    
       // using Enumeration to print all the keys in the Hastable
       e = h.keys();
       System.out.println("Printing out all Keys in Hashtable");
       while (e.hasMoreElements())
        {
         System.out.println( e.nextElement());
        }
    
       //print hashTable as string
       System.out.println("hastable in string - " + h.toString() );
    
       // "contains" compares object supplied to all elements using ".equals()" method
       // and returns a boolean true if its found.
       if ( h.contains("parker") ) System.out.println(" \"parker\" is an element");
    
       // "containsKey" compares object supplied to all keys using ".equals()" method
       // and returns a boolean true if its found.
       if ( h.containsKey("peter") ) System.out.println(" \"peter\" is a key");
    
       //remove a key/element from the hash table
       h.remove("peter");
       h.remove("clark");
       h.remove("tony");
       // Check if Hashtable is empty
       if (h.isEmpty()) System.out.println("Hastable is empty");
    
     }
    
    
    }
    
    
    

    Packages:


     If you don't specify a package at the top of your source file- all the classes defined will belong to the default class.  Classes inside the same package can see each other, and each other's methods and variables- unless they are labeled "private".  If private then other classes, including sub-classes, cannot access them.  To make methods and variables available to sub-classes make them "protected".   Classes outside the package can only see those objects, methods, and variables that are labeled "public".  You should use "protected" sparingly. Sub-classes should access their super-classes through public methods the same as other classes.

    "Is a", "Has a":


      Inheritance should be used when there is a "Is a" relationship between objects.  When the sub-class would be a special case of the super-class.  Don't inherit when there is a "Has a" relationship.  For instance a "Employee" class should not be sub classed for "Salaried Employee", and "Hourly Employee".  Rather than saying a Hourly Employee "is a" Employee- we should say a Employee "has a" status which is "hourly", or "Full Time".  The status can be variable that points to a object held in a reference to an object- "EmployeeType"
     
     


    Reflection:


    Reflection allows you to examine objects at run time.
    To get a list of all the fields of a object use:
     Class c = object1.getClass();           //Get Class of this instantiated object.
     Field [] fieldsArray = c.getDeclaredFields();     //Get a Array of "Field" objects representing every variable defined in the class
     try {  fieldsArray[1].set(objhect1,h.get( f[k].getName() ) ); }
    
    This example will examine an Object and if any of its variable name are also found in the passed Hashtable it will set them to the vaule for that key in the hash. You might use this when loading object states from a file to a DB. Will only work for strings as written.
    import java.util.*;
    import java.lang.reflect.*;
    
    class T
    {
      public static void main (String args[] )
        {
         T t = new T();
         t.doIt();
        }
     private void doIt()
       {
        Record r = new Record();
        Hashtable h = new Hashtable();
        h.put("title_id","TITLE-ID");
        h.put("type","TYPE");
    
        setObjectStringFieldsFromHash(r,h);
        System.out.println("R title_id=" + r.title_id + " R type = " + r.type );
       }
    
     public static void setObjectStringFieldsFromHash(Object o, Hashtable h)
     {
       Field [] f;
       Class c = o.getClass();
       f = c.getDeclaredFields();
       for ( int k = 0; k < f.length; k++)
         {
           System.out.println("F Name =" + f[k].getName() );
           if ( h.containsKey(f[k].getName()) )
             {
               try {  f[k].set(o,h.get( f[k].getName() ) ); }
               catch (Exception e) { System.out.println("Exception=" + e.getMessage()); }
              }
         }
      }
    }
    

    Observer/Observable Pattern:


    A Observable class extends class "Observable", inheriting its addObserver(), notifyObservers, and setChanged methods. A Observer class implements the Observer interface requiring it to supply a update() method. The Observable object will tell its Observers when something they need to know about has happened by invoking it's notifyObserver() method. This calls the update() method of each Observer object that has been registered with the Observable object by passing it's object refernece to the addObserver() method. The setChanged() method sets the "state changed" flag to true. The notifyObservers() method checks that this flag is true, calls each observer's update method, and then sets the flag back to false.
    import java.util.*;
    
    class Test
    {
      public static void main (String args[] )
        {
         Test t = new Test();
         t.doIt();
        }
    
     private void doIt()
       {
         ObservableExample os = new ObservableExample();
         ObserverExample o = new ObserverExample();
         os.addObserver(o);
         os.doSomethingWorthTelling();
       }
    
    }
    
    ------------------------------------------------------------------
    import java.util.*;
    
    class ObserverExample implements Observer
    {
    
     public void update(Observable observable, Object o)
        {
         System.out.println( ((String)o) );
        }
    
    }
    
    ------------------------------------------------------------------
    
    import java.util.*;
    
    public class ObservableExample extends Observable
    {
      public void doSomethingWorthTelling()
        {
          setChanged();
          notifyObservers("Hi there");
          setChanged();
          notifyObservers("Bye now");
        }
    
    }
    

    Example: IPSignalCatcher

    --------------------- Test.java ------------------------------------
    import JDTools.*;
    import java.util.*;
    import java.lang.reflect.*;
    
    /**
     *  This test application will print "Debugging Off" once a second.
     *  It instantiates a IPSignalCatcher class to listen for Telnet connections on port 5050.
     *  If the user Telnets to port 5050 while this application is running and types "debug=yes",
     *  the program will start printing "Debugging On" instead.
    */
    
    class Test implements Observer
    {
      boolean debug;
    
      public static void main (String args[] )
        {
         Test t = new Test();
         t.doIt();
        }
    
     private void doIt()
       {
         Runnable ipsc = new IPSignalCatcher(this,5050);
         while (true)
           {
             try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
             if (debug) System.out.println("Deguggin On");
             else       System.out.println("Debugging Off");
    
           }
      }
    
     public void update(Observable observable, Object o)
        {
          System.out.println("Was updated by IPSignalCatcher, String passed = " + ((String)o) );
          if ( ((String)o).indexOf("debug=yes") != -1 )  debug = true;
          if ( ((String)o).indexOf("debug=no")  != -1 )  debug = false;
        }
    
    }
    
    ----------------   IPSignalCatcher.java  -------------------------------------
    
    import java.util.*;
    import java.net.*;
    import java.io.*;
    
    /**
     * @IPSignalCatcher
     * @version     1.0, 02 Dec 1998
     * @author: John Donohue
     *
     *   The purpose of this class is to provide a way of signaling a running Java application from a Telnet client
     * across the network.  The class listens for connections (under a seperate thread) for IP connections.
     * Once the connection is made the server accepts a single line of input (terminated by \n) and then kills
     * the connection, and returns to listening for new connections.  The input line is sent to the Observer's
     * of this class so that they can act on it.
     * For example: If you have a Java application running as a Daemon, and you wish to tell it to begin
     * writing debuggin messages to a log without stopping and starting it, you could use this class.
     * Your application would Observe this class and react to its update method being with a string
     * "debug=yes" being passed.   To send the string telnet to the IP and port, and type the string.
     */
    
    public class IPSignalCatcher extends Observable implements Runnable
    {
     int port;
    
     public IPSignalCatcher(Observer o, int portIn)
       {
         this.addObserver(o);
         Thread th = new Thread(this);
         th.start();
         this.port = portIn;
       }
    
    
     public void run()
       {
        ServerSocket server;
        Socket connection;
        InputStream input;
        char c;
        String s;
        StringBuffer sb;
    
        try
          {
           server = new ServerSocket(port, 100);
           while ( true)
            {
              connection = server.accept();
              input = connection.getInputStream();
              sb = new StringBuffer();
    
              while ( (c= (char)input.read() ) != '\n')
                {
                  sb.append(c);
                }
              connection.close();
              s = new String(sb.toString());
              setChanged();
              notifyObservers(s);
            }
          }
        catch (IOException e)
          {
             e.printStackTrace();
             System.out.println("Message=" + e.getMessage());
          }
      }
    
    }
    

    Example: of a Singleton object

       A Singleton is a class that should only exist once. We can enforce this by making it's constructor private so that only the class itself can instantiate itself. Other classes will call a custom getInstance() method to instantiate the class. The first call to getInstance() instantiates a Singleton object and returns a reference to it. Subsequent calls will appear to work, but will simply be returning references to the existing Singleton.
    import java.util.*;
    
    class Test 
    {
      public static void main(String [] args )
        {
          Test t = new Test();
          t.doIt();
        }
    
      public void doIt() 
        {
          //Singleton s = new Singleton();                  //This won't work as the constructor is private
          Singleton s2 = Singleton.getInstance("First");    // Prints "First"
          System.out.println(" String is = " + s2.s);
          Singleton s3 = Singleton.getInstance("Second");   // Will not print "Second"
          System.out.println(" String is = " + s3.s);
        }
    }
    ......................................
    
    class Singleton
     {
       static Singleton instance = null;
       static String s; 
    
       // To instatiate new Singleton's other class's must call this getInstance() method. 
       public static Singleton getInstance(String sIn)  
        {
          if ( instance == null) instance = new Singleton(sIn);
          return instance;  
        }
    
      private Singleton(String sIn)  // Make constructor private so that only this class can instantiate itself
        {
         this.s = sIn;
         System.out.println("Singleton's Constructor was called.  String set to " + s );
        }  
    
     }