Random jumble of notes for taking the certification exam and java snippets.

  1. Wrapper Classes:

    Each primitive type has a wrapper class to provide static utilities and the ability to live in container classes like Vector. The wrapper classes are Byte, Short,Character, Integer, Long, Float, Double, and Boolean.

    Wapper classes are immutable, their value cannot be changed once it is set.

    MIN_VALUE is the smallest negative number for Integer classes, but for floating points its the smallest positive number.

    Operations cannot be done on wrapper classes; no "+","-", operators are defined.

    the Integer and Long wrapper classes have toBinaryString() and toHexString() to view the contents in other bases more easily.

    Integer.toBinaryString(1028) // prints "10000000100"

    Example:

    public static void main(String argv[]) {
    int eight = 8;
    int six = 6;
    int four = 4;
    
    System.out.println("eight: \"" + Integer.toBinaryString(eight)+ "\"");
    System.out.println("six: \"" + Integer.toBinaryString(six)+ "\"");
    System.out.println("four: \"" + Integer.toBinaryString(four)+ "\"");
    
    System.out.println("eight | six: \"" + 
       Integer.toBinaryString(eight | six) + "\"");
    System.out.println("eight & six: \"" + 
       Integer.toBinaryString(eight & six) + "\"");
    System.out.println("eight | four: \"" + 
       Integer.toBinaryString(eight | four) + "\"");
      } // function main()
    

    Top rated books on Java Programming:

  2. Bitshift operators

    FYI: To convert a negative binary number to positive, flip all the bits and add '1'.

    Bitwise shift note: ">>" shifts bits to the right and retains the sign. ">>>" shifts in zero bits, so the number will be positive.

    int eight = 8;
    int six = 6;
    int four = 4;
    
    System.out.println("eight \"" + Integer.toBinaryString(eight ) + 
    "\" >>> 2 : "+Integer.toBinaryString( eight >>> 2 ) + "\"");
    System.out.println("eight \"" + Integer.toBinaryString(eight ) + 
    "\" >>> 3 : "+Integer.toBinaryString( eight >>> 3 ) + "\"");
    System.out.println("eight \"" + Integer.toBinaryString(eight ) + 
    "\" >>> 4 : "+Integer.toBinaryString( eight >>> 4 ) + "\"");
    
    eight *= -1;
    
    System.out.println("eight \"" + Integer.toBinaryString(eight ) + 
    "\" >>> 2 : "+Integer.toBinaryString( eight >>> 2 ) + "\"");
    System.out.println("eight \"" + Integer.toBinaryString(eight ) + 
    "\" >>> 3 : "+Integer.toBinaryString( eight >>> 3 ) + "\"");
    System.out.println("eight \"" + Integer.toBinaryString(eight ) + 
    "\" >>> 4 : "+Integer.toBinaryString( eight >>> 4 ) + "\"");
    

    Produces:

    eight "1000" >>> 2 : 10"
    eight "1000" >>> 3 : 1"
    eight "1000" >>> 4 : 0"
    eight "11111111111111111111111111111000" >>> 2 : 111111111111111111111111111110"
    
    eight "11111111111111111111111111111000" >>> 3 : 11111111111111111111111111111"
    eight "11111111111111111111111111111000" >>> 4 : 1111111111111111111111111111"
    

    Note that the above last two lines are getting narrower, implying a "0" and "00" in front of the result, although toBinaryString() drops leading zeros, it should be read as,

    eight "11111111111111111111111111111000" >>> 3 : 011111111111111111111111111111"
    eight "11111111111111111111111111111000" >>> 4 : 001111111111111111111111111111"
    
    
    Fragment to print binary number directly:
    byte number = 48;
    int i = 256; //max number * 2
    while( (i >>= 1) > 0) {
    System.out.print(((number & i) != 0 ? "1" : "0"));
    }
    
  3. Four types of primitives:
    1. integers
    2. characters
    3. floating point
      1. float, 32 bits
      2. double, 64 bits
    4. boolean
    5. true or false
  4. Java types and ranges
    Type Bits Bytes Lowest Highest
    boolean 1 1 false true
    char 16 2 '\u0000' '\uffff' (65535)
    byte 8 1 -128 +127
    short 16 2 -32,768 +32,767
    int 32 4 -2^31 (-2,147,483,648) 2^31 -1 (+2,147,483,647)
    long 64 8 -2^63 (-9,223,372,036,854,775,808) 2^63 -1 (+9,223,372,036,854,775,807)
    float 32 4 ±1.40129846432481707e-45 ±3.40282346638528860e+38
    double 64 8 ±4.94065645841246544e-324 ±1.79769313486231570e+308
  5. Notes on constants and types:

    Four data types: primitives, classes, interfaces, and arrays. variables contain either primitive values or refer to objects.

    an integer constant is assumed to be 32bit, but a floating point constant is assumed to be long, or 64 bit

    Examples of constants:

    24 // a 32 bit integer
    24L // a long (64 bit) integer
    012 // an octal constant
    123.4 // a double
    0xFFAA // a hexidecimal number

  6. Type Conversions

    "char" and "boolean" have no implicit type conversion from other types, although a "char" may be set to an integer constant within its range.

    int i = 100;
    char c = 100; //ok
    c = 66000; //illegal, too big of a constant
    char c = i; //illegal 
    c = (char)i; //ok
    c = (char)65536; //compiles and runs, but constant is too big; 
                     //will drop first two bytes to give 0
    
    byte b = 128; // won't compile constant too big
    byte bb = (byte)128; // compiles and runs; bb is -128
    

    When char, byte, and shorts are used in operations, their values and the result are ints.

          short s1 = 120,s2=20,s3;
          s3 = (short) s1 * s2; //not quite, won't compile
          s3 = (short) (s1 * s2); //ok
    
  7. Arrays

    When arrays are intialized all primitive types are set to their default value (integers to zero, floats to 0.0, booleans to false, and objects are set to "null").

    int list[] = new int[10];
    int coins[] = {1,5,10,25};
    String foods[][] = {             // a two dimensional array
       {"apples","pears","oranges"},
       {"beets","ocra","beans"}
    };
        //create a string array
        String quarks[] = new String[2];
        quarks[0]  = "top";
        quarks[1]  = "bottom";
    
  8. chars

    chars are really 16 bit positive integers designed for unicode. To set a value use the '\u' prefix. For example,

    char myChar = '\u0058' // is the letter X

  9. equals
      public boolean equals(Object obj)
    
    Compares two Objects for equality.

    The equals method implements an equivalence relation:

    • It is reflexive
    • : for any reference value x, x.equals(x) should return true.
    • It is symmetric
    • : for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
    • It is transitive
    • : for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
    • It is consistent
    • : for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false.
    • For any reference value
    • x, x.equals(null) should return false.
  10. Access modifiers

    Classes declared as "final" cannot be extended, like StringBuffer. "public" means anyone can see this method or variable. "protected" means the member can only be seen by this class, anything that extends this class AND other classes in the same package. "private" means only this class can see this method or variable (by default they are not even shown in javadoc).

  11. Nested Classes

    Java allows classes to contain other classes. Java has two types of nested classes, "static" ones which are usually refered to as "nested" and "member" classes as "inner" (although "inner" classes are also nested).

    1. Nested static

      Can only refer directly to parent's static variables and methods. To reference local variables, a parent object reference is needed.

      public class StaticInnerExample {
      
          static int i;
          StaticInner si = new StaticInner();
      
          public static class StaticInner {
          public void write() {
              System.out.println("i: \"" + i++ + "\"");
          }
          }
      
          public static void main(String[] args) {
          StaticInnerExample sie = new StaticInnerExample();
              sie.si.write();
              sie.si.write();
          }
      
      }
      
    2. Member (NonStatic) Inner class
      1. Notes
        1. Can refer directly to parent's variables and methods.
        2. Since a member inner class cannot exist without an instance of its enclosing class, it cannot have static members.
        3. Any accessibility modifiers may be used with an inner class.
        4. To get a reference to the enclosing class, a special form of the "this" operator is used, "EnclosingClassName.this".
        5. To create an instance of an inner class from outside its containing class, a special form of the new operator is used, "outerClassInstanceName.new InnerClassName()".
      2. Local Inner class

        These are defined within a method. They can only see variables marked as "final".

        public class LocalInnerExample {
        
        public static void main(String[] args) {
            final int k = 1;
            class ImALocalInner {
            public void write() {
                System.out.println("writing. k="+k);
            }
            }
            new ImALocalInner().write();
        }
        }
        
      3. Anonymous Inner class
  12. Notes on Object Hierarchy
    1. References to member variables are resolved at compile time, references to methods are computed at runtime.
    2. When overriding a method (i.e., same signature) the return type must be the same, the access modifiers may not be more restrictive, and the exceptions thrown may not be more general.
    3. When a child class contains a variable with the same name as one of its ancestor's classes, it is called "shadowing", and not usually recommended.
  13. Misc
    1. finalize()

      After an object has been marked for garbage collection, and before it's space is havested by the grim reaper, the following method is invoked:

      protected void finalize() throws Throwable
      

      You can beg the jvm to run it by invoking, "System.runFinalization()", but if it doesn't feel like it, it doesn't have to.

    2. Interfaces can extend other Interfaces, but no root Interface (like Object) exists.
    3. To print the classname of an object: obj.getClass().getName()
    4. using Properties files (seems a little heavy to me now, java has better libraries now for them):
          String initFile = "C:/t1.prop";
          FileInputStream fileInputStream = null;
          try {
          fileInputStream = new java.io.FileInputStream(initFile);
          }
          catch(FileNotFoundException e) {
          String message = "prop file not found, \""+initFile+"\"\n
      "; throw (new Exception(message+"\n
      "+e)); } try { properties = new Properties(); properties.load(fileInputStream); } catch(Exception e) { String message = "Properties file could not be read from, "+initFile+". "+e; throw (new Exception(message)); }
    5. File Notes:
      1. Instead of PrintStream use PrintWriter since its unicode compliant
      2. InputStream and Reader are abstract
      3. equals() must have the same type of object, otherwise its false
      4. synchronize() must have an object, not just a primitive (eg int i; synchronize(i) { ...} won't work - it needs an object)
    6. fragment to read a file, line by line
          String thisLine = null;
          StringBuffer lineStringBuffer = new StringBuffer("");
          try {
          BufferedReader myInput
              = new BufferedReader(new FileReader(filename));
          while ((thisLine = myInput.readLine()) != null) {
              lineStringBuffer.append(thisLine).append("\n");
          } // while loop ends here
          } // end try
          catch (Exception e) {
          System.out.println("getFileContentsAsStringError(): " + filename + "\n" + e);
          throw e;
          }
      


    7. Create a file and write some stuff to it
          PrintWriter out
          = new PrintWriter(new BufferedWriter(new FileWriter("test.out")));
          out.println("test");
          out.close();
      


    8. How to write a stacktrace to a string
          catch(Exception e) {
              StringWriter writer = new StringWriter();
              e.printStackTrace(new PrintWriter(writer));
              String trace = writer.toString();
              throw(new Exception("Problem opening file \"" + XMLFilename +"\".\n
      "+ trace + e)); }


    9. Defining a constructor as private, makes it uninstantiable.

      This would be useful if a class is used only to store variables and static methods, or if its a Singleton.

    10. To sleep or wait for a few milliseconds:
         try { Thread.sleep(7000);} catch (Exception e ){}
      


    11. to convert from String to Int,
      int x = Integer.parseInt("42");
      


    12. to convert from Int to String,
      String asdf = String.valueOf(10);
      



      or the cheesy way
             String asdf = ""+10;
      


    13. to show string in status area of a browser from an applet:
              getAppletContext().showStatus("My status String");
      


    14. Invoke a static method on a class with the dot operator and the name of the class
             i = Integer.parseInt("42");
            
      
    15. To use setCursor(), you need to know the frame. Here's a little snipet of code to get the frame and set the cursor in an applet.
    16.        // make this global
             Frame myFrame;
      
          Component c = this;
          while (c != null && !(c instanceof Frame)) {
            c = c.getParent();
          }
          myFrame = ((Frame)c);
          myFrame.setCursor(Frame.WAIT_CURSOR);
            
      
    17. To have one constructor call another use the "this" keyword. This must be the first line of the contructor:
      /***
       * Shows an example of one constructor calling another
       * 
      **/
      public class Example1 
      {
      Example1(int i)
        {
          System.out.println("i: " + i);
        }
      Example1()
        {
          this(0);
        }
        public static void main(String argv[])
        {
          new Example1(5);
          new Example1();
        }
      }
      

      If you don't specify a constructor, the compiler will provide a no argument constructor for your class (except when the immediate super class has no empty constructor).

    18. To show timestamp using SourceSafe keywords:
      Label TimeStampLabel = new Label("$Modtime: 1/29/98 9:53a $");
      
    19. To translate a url into http transmissible format
    20.          myString = java.net.URLEncoder.encode(myLucid);
      
    21. Wierd thing about AND operators:
    22. If both operands are of type boolean:
      & - evaluates both
      && - evaluates the left side, if true the right side is also evaluated.
    23. gridbag code:
    24. String Tokenizer code:
           import java.util.StringTokenizer;
      
           StringTokenizer st = new StringTokenizer("this is a test"," ");
                while (st.hasMoreTokens()) {
                   System.out.println(st.nextToken());
               }
          
      
    25. to flush print buffer:
           System.out.print(".");System.out.flush();
      
    26. Function to return a web page given a URL
      /***
       * returns a web page given a URL
       * @param urlString the address to get
       * @param linenumbers if true the linenumbers are prepended to each line
      **/
      public static String getWebPage(String urlString, boolean linenumbers)
        {
          String line = null;
          URLConnection uc = null;
          StringBuffer desc = new StringBuffer();
      
          try {
          uc = new URL(urlString).openConnection();
          BufferedReader sin = new BufferedReader(new InputStreamReader(uc.getInputStream()));
          int i=0;
          while((line = sin.readLine()) != null) {
              if(linenumbers) {
              desc.append("\n"+i+": ");
              i++;
              }
              desc.append(line);
          }
           sin.close();
          }
          // try
          catch (Exception ex)
          { 
              System.out.println("Exception thrown: " + ex);
              ex.printStackTrace(System.out); 
          }
      
          return new String(desc);
        }
      
    27. List the methods of an object

      (When you just can't trust the documentation, or you want to do something really interesting)

      Method[] methods = new String("test").getClass().getDeclaredMethods();
      for(int j=0;j<methods.length;j++) {
      	System.out.println(methods[j].toString());
      }
      
    28. Code to access property file and get info from an ini file.

      the contents of the ini file are lines like, "proxyname = myproxy"

      public void init() {
      	try {
      	FileInputStream in = new FileInputStream("SurveyTaker.ini");
      	applicationProps = new Properties();
      	applicationProps.load(in);
      	in.close(); //should be in finally
      } catch (Exception e) {
      System.out.println("Exception City"+e);
      	System.exit(1);
      }
      	dbf = DocumentBuilderFactory.newInstance();
              dbf.setValidating(false);
              getWebPageThruProxy = new GetWebPageThruProxy( 
      	(String)applicationProps.getProperty("proxyname"),
      	(String)applicationProps.getProperty("portnumber"),
      	(String)applicationProps.getProperty("username"),
          (String)applicationProps.getProperty("password"));
      ...
      
    29. Evaluate an XPath expression

       /**
           * @param doc the xml document to search for radio buttons
           * @return string to append to the URL
           * @throws Exception
           */
          public String getRandomChoicesFromInputRadioButtons(Document doc) throws Exception {
              StringBuffer tmp = new StringBuffer();
              NodeIterator nl = XPathAPI.selectNodeIterator(doc, "//input[@type='radio']");
                org.w3c.dom.Node n;
                while ((n = nl.nextNode())!= null)
                      {        
                        System.out.println(" $$$$$$$$$$$$$$ node name="+
      		     n.getAttributes().getNamedItem("name").getNodeValue());
                        System.out.println("                        node value="+
      		     n.getAttributes().getNamedItem("value").getNodeValue());
                        System.out.println("                        node title="+
      		     n.getAttributes().getNamedItem("title").getNodeValue());
                         }
         
              return tmp.toString();
          }
       
      
    30. Function to simulate __LINE__ from C preprocessor and tell what line number the java program is executing
      /***
       * Prints the location of the current thread.  This should be used from 
       * functions in other files since it clips the first few lines in the
       * stack trace.
       * when the following line is placed in source code:
       *
      IQUtil.printWhereAmI(); * *
      It produces: *
      **printWhereAmI(): at org.fincher.surveys.takeSurveys(SurveyTaker.java:177) * * @optimize I think the trimming of the first two lines could be improved. * @author mitch fincher **/ public static void printWhereAmI() { //create exception and write its stack trace to a String StringWriter sw =new StringWriter(); PrintWriter pw =new PrintWriter(sw); new Exception("printWhereAmI()").printStackTrace(pw); pw.close(); String exceptionText = sw.toString(); //skip through first two "at ..." for(int i=0;i<2;i++) { exceptionText = exceptionText.substring(exceptionText.indexOf("at ",1)); } //clip off remaining stack trace System.out.println("\n **printWhereAmI(): " + exceptionText.substring(0,exceptionText.indexOf("at ",1))); }
    31. Using Regular Expressions for string manipulations

      replaceFirst and replaceAll replaces using regular expressions. In the following example the first space character is replaced with an X.

      String startURL = args[0].replaceFirst("[ ]","X");
      
    32. to time an operation:
      long startTime = System.currentTimeMillis();
      
         // Operation to be timed goes here
      
      long elpasedTime = System.currentTimeMillis() - startTime; 
      or
      System.out.println("millisecs: \"" + 
         (System.currentTimeMillis() - startTime) + "\"");
      
      
    33. to exit a standalone java application:
            System.exit(0);
      
    34. Building and compiling to use a jar file on windows, put the actually filename in the classpath variable (not just the directory location).
      set classpath=%classpath%c:\fincher\java\jrun.jar
      
    35. size(), length, or length()? (This is an annoyance).
      Object Size Put Get
      Vector size() addElement() elementAt(i)
      String length
      Array length()
      Hash size() put("key",object) get("key")
    36. To read a string from the user:
        System.out.print("Enter your name:");System.out.flush();
        while ( (ch = (char)System.in.read()) != '\n')
        {
          name = name + ch;
        }
        System.out.println("Your name is: " + name);System.out.flush();
      }
      
    37. How to convert a String to an InputStream

       byte[] bytes = "ImaString".getBytes();
       ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
      
    38. How to write a copyright symbol

      Use our old friend character 169.

       drawString(titleColor, elementNameFont[2],  "Copyright "+ (char)169 +" 2001-2007 some rights reserved by Mitch Fincher.", x,y);
      
    39. Vector tips
      List FilterList;
      FilterList = new List(6,false);
      Vector choiceVector = new Vector();
      choiceVector.addElement("first choice");
      choiceVector.addElement("second choice");
      choiceVector.addElement("third choice");
      ...
        for(int i=0;i<choiceVector.size();i++)
        {
           FilterList.addItem((String)choiceVector.elementAt(i));
        }
      
    40. Javadoc - the way to document code. Overview:
      /***
       * Description goes here.
       *
       * @author       (classes and interfaces only, required)
       * @version      (classes and interfaces only, required) (see footnote 1)
       *               
       * @param        (methods only)
       * @return       (methods only - will eventually become @returns)
       * @exception    (will eventually become @throws)
       *               
       * @see          
       * @since        
       * @deprecated   (see How and When To Deprecate APIs) * @param
      **/
      
      I use the following blank for methods
      /***
       * 
       *
       *                
       * @param       
       * @param       
       * @return       
       * @exception     
       *               
       * @see          
      **/
      

      note: for the @see parameter, use just the class name as an argument, or if it is a method, separate it from the class with '#', eg, @see myClass#myMethod

      see Sun's java doc Home Page for more details.
    41. Common Errors I've committed
      1. "ClassDef not found: ClassA".

        Sometimes ClassA can actually, maddeningly, be found right in the same directory, but ClassA cannot find one of the classes that it needs. Unfortunately the error message from java is not quite descriptive enough.

      2. Using "run()" instead of "start()" to kick off a thread.
    42. Interesting functions in Java
      1. finalize() for all classes.
      2. This is called before an object is reclaimed, and used to free resources. Important note: unlike constructors, the finalize method does not automatically call its parents finalize, so it must be called explicitly.
        public void finalize() throws Throwable {
         if(connection != null)
             connection.close();
         connection = null;
         System.gc();
              
         super.finalize();
        }
        
      3. dispose() for classes Frame and Window. This releases class resources, so garbage collection is easier. Example:
        hide();
        this.dispose();
        
    43. Prints all the system properties

      System.getProperties().list(System.out);
      
    44. A way to get the current working directory

      System.out.println(new File("").getAbsolutePath());
      
    45. JDBC Notes:
      1. prepareCall() is used to execute stored procedures
      2. Connection methods for committing and rollback of statements
        1. connection.setAutoCommit(false); // it defaults to true
        2. connection.commit(); // commits all previous uncommited statements.
        3. connection.rollback(); // rolls back all previous uncommited statements
    46. Servlet Notes:
      1. Servlet lifecycle
        1. Servlet environment creates the servelet
        2. calls the init(Servletconfig) method once. No service() request will be performed until init() is run.
        3. runs instances of the service() method
        4. calls the servlet's destroy() method
        5. instance of Servlet is garbage collected (and its finalize() method invoked).
    47. Compiler and Runtime options
      Example runtime command line setting the maximum memory to 128meg and 
      turning off the runtime compiler so stacktrace works better:
      % java -Djava.compiler=NONE  -Xmx128m Mayan2
      
      -Xmsn 
      Specify the initial size of the memory allocation pool. 
      This value must greather than 1000. To multiply the value by 1000, 
      append the letter k. To multiply the value by 1 million, append the letter m. 
      The default value is 1m 
      -Xmxn 
      Specify the maximum size of the memory allocation pool. 
      This value must greather than 1000. To multiply the value by 1000, 
      append the letter k. To multiply the value by 1 million, append the letter m. 
      The default value is 64m
      //a possible way to launch a process from java and wait till it finishes 
         Runtime runtime = Runtime.getRuntime();
         Process process = runtime.exec("some command goes here....");
         int returnCode = process.waitFor();
      
      
      
      to profile code
      java2 -Xrunhprof:help
      use doe=y|n
      
      
      In java1.2.2, to achieve the affect of "-nojit" use,
      java -Djava.compiler=NONE
      
    48. Example of using Generics and "foreach" loop in Java 5

      java.util.ArrayList<String> names = 
                             new java.util.ArrayList<String>();
      names.add("mike");
      names.add("frank");
      names.add("sarah");
      // cannot do   names.add(10);
      
      for(String name: names) {
          System.out.println("name= " + name);
      }
      
    49. Example Ant file

      Demonstrates passing variables on the command line

      
      <?xml version="1.0"?>
      <project name="SurveyDirectorTaker" default="build" basedir=".">
          <description>  This file builds SurveyTaker and runs a test taking arguments
              Example:
              ant test -Dh=aus158 -Dg=Baseline -Dn=10 -emacs
          </description>
          <property name="basename" value="SurveyDirectorTaker"/>
          <property name="n"  value="2" description="number of repeats" />
          <property name="h"  value="sdfarm.austin.intelliquest.com" description="host server" />
          <property name="g"  value="uk atp" description="group name"/>
      
          <target name="init" > 
             <tstamp> 
                    <format property="TSTAMP" pattern="hh:mm aa" locale="en"/>
             </tstamp>
             <echo message="${TODAY} ${TSTAMP}. OS: ${os.name} java.os:${ant.java.version}"/>
          </target>
      
          <target name="clean">
              <delete file="${basename}.class">
              </delete>
          </target>
      
          <target name="build" depends="init,clean" description="compiles the source code" >
             <javac srcdir="." compiler="javac1.4" verbose="true">
           <classpath>
            <pathelement location="./Tidy.jar"/>
          </classpath>
               </javac>
          </target>
      
          <target name="test"  >
             <java classname="${basename}" classpath=".;Tidy.jar" dir="." fork="true">
             <arg value="http://${h}/SurveyDirector/Engine.aspx?sd_group=${g} ${n}" />
             <arg value="${n}" />
             </java>
          </target>
      
      </project>
      
      
      
      
    50. How to embedd the compile date into the code

      This tip from Mike Phillips:

      I had to come up with a more complex solution. We use Netbeans, and everything is compiled with ant tasks. I created this property file task inside inside the build.xml. Now I have a property file that contains an identifying source of the version build and the date.
          <target name="-pre-compile">
            <propertyfile
                 file="${src.dir}/webapp/bundles/version.properties"
                 comment="Do not edit, this file generated at complie time.  This property file identifies the source and time of the application build">
               <entry  key="version.id" value="${version.id}"/>
               <entry  key="version.date" type="date" value="now" pattern="EEE MMM d HH:mm:ss z yyyy"/>
             </propertyfile>
          </target>
      

      You can read the properties file with a line like:

        public String getVersion()
        {
          String dateVal = ResourceBundle.getBundle("webapp/bundles/version").getString("version.date");
          String id = ResourceBundle.getBundle("webapp/bundles/version").getString("version.id");
          return id + " " + dateVal;
      
        }
      
    51. Mitch's personal java tips:
      1. Use JUnit for testing - a good intro is at www.admc.com/blaine/howtos/junit/junit.html.
      2. NEVER ignore an exception
    52. Examples of some of my Java classes. Some I wrote way back in 1997 and are really dated now.
      Date Source Description
      2004/11 SurveyDirectorTakerTest.java Junit Example.
      2003/08 XhtmlChecker.java A small spider that checks my site for xhtml compliance.
      2003/04 GetWebPageThruProxy.java A tiny class that uses BASE64Encoder from Sun that can tunnel through a proxy server and get web pages.
      2002/12 SiteChecker.java A small personal spider that checks your site for xhtml compliance.
      2002/01 DateRenamer.java A tiny application to prepend the date infront of the filename - I know, its easier in perl.
      2001/12 TimeOut.java A deprecated example of how to limit the time of a thread (when you can't control the programming of the thread).
      2000/05 ValidateXML.java A tiny application to grab a series of pages and check for valid xml
      2000/05 GetWebPage.java A tiny application to grab the raw html from a web server
      2000/02 XMLObject.java A simple XMLObject parent class that can instantiate java classes from the XML elements
      2000/02 TestServlet.java A test servlet that prints the properties from the System object so the environment of a servlet can be known
      2000/02 JPythonTest.java An example of interfacing java code to JPython
      1999/12 CreateObjects.java A sample showing how to use the "Class" class to create any type of object given its name as a string
      1999/10 WriteJPEGDimensions.java A sample using JPEG extensions to write the HTML image tag for JPEG files
      1998/10 showProperties.java A small application to demonstrate enumeration and System.getProperty() function.
      1998/10 ThreadExample3.java A really tiny application to demonstrate multi-threading.
      1998/10 ThreadExample2.java A really tiny application to demonstrate multi-threading.
      1998/10 ThreadExample.java A really tiny application to demonstrate multi-threading.
      1998/10 SiteLoader.java StandAlone application to load sites for performance testing.
      1998/10 SerializableResultSetMetaData.java An implementation of ResultSetMetaData that can be used with SerializableResultSet.
      1998/10 SerializableResultSet.java An implementation of ResultSet that can be serialized over the net.
      1998/10 ListFiles.java shows all files in a tree above a certain size.
      1998/10 ExceptionExample.java Exampleof using Exceptions.
      1998/10 ExampleInstanceof.java A small example showing how to use "instanceof" to retrieve items froma Vector.
      1998/10 EventExample.java tiny example of 1.0 event model with handleEvent and action.
      1998/10 DisplayClassInfo.java displays the interfaces, methods and fields of a class using theReflect package.
      1998/10 ApplicationServlet.java An example of a Servlet that can also be run as an application.
      1998/10 ApplicationAndApplet.java Sample program that runs as a standalone application or an applet.
      1997/4 Arbor.java Creates a tree using Java1.1 listners, graphicscanvas and a few controls.
      1996/10 mayan.java Mayan Periodic Chart. Shows use ofgraphics, arrays, cursor tracking.
      1996/10 HelloWorldServlet.java A tinyexample of a Servlet getting a parameter.
    53. More Misc Notes
      All of the Math package is static, only methods and constants, no objects.
      
      
      Division by zero in integer arithmetic throws "ArthmeticException",
      but in floats it returns a value of Float.NaN.
      
      
      
      unused reserved words in java 2.0:
      byvalue, cast, const, future, generic, goto, inner, operator, outer, rest, var.
      
      identifiers for variables, classes, and methods begins with a letter,
      $, or _.  ($'s are typically reserved for the compiler for creating inner classes).
      
      
      The == operator on objects only tests if the objects are the same
      object, not if they contain the same contents.  To test contents use
      the Object.equals() method.
      
      
      To convert a querystring into a hashtable:
          Hashtable hashtable = javax.servlet.http.HttpUtils.parseQueryString(req.getQueryString());
      
      The unary complement operator for integers is the "~", for boolean it
      is "!".
      
      The conditional assignment operator is the only tertiary command in
      java.  Example:
      
      a =    x > 0 ? x : 0;  // this assign a to x if positive (ok, ok,
      non-negative), otherwise assigns it to 0.
      
      
      
      Example of Enumeration (you should really use iterators in 1.2.2)
          for (Enumeration e = property.propertyNames() ; e.hasMoreElements() ;) {
            System.out.print(propertyElement = (String)e.nextElement());
            System.out.println(" = " + System.getProperty(propertyElement));
          }
       
          for (Enumeration e = java.sql.DriverManager.getDrivers(); e.hasMoreElements() ;) {
          System.out.print(d = (Object)e.nextElement());
          System.out.println("java.sql.DriverManager.getDrivers() = " + d.getClass().getName());
          }
      
      Example of Iterator
          for (java.util.Iterator i = childrenArrayList.iterator(); i.hasNext() ;) {
              xmlObject = (XMLObject)i.next();
                  System.out.println("xmlObject: " + xmlObject);
              }
      
      
      public static String dumpHashMap(HashMap hashmap)
      {
          StringBuffer desc = new StringBuffer("dumpHashmap:");
          for (Iterator i = (hashmap.keySet()).iterator() ; i.hasNext() ;) {
          Object key = i.next();
          Object obj = hashmap.get(key);
          desc.append("\n  \""+key+"\" --> \"" + obj+"\"");
          }
          
          return new String(desc);
      }
      
      
      
      
      Example of reading properties from a properties file somewhere in the classpath(by Ken Beckect:
      Properties dpProps = new Properties();
              InputStream is = getClass().getResourceAsStream("dp.properties");
      
              try {
                  dpProps.load(is);
              }
              catch (IOException ioe) {
                  ioe.printStackTrace();
              }
      


    54. Eclipse Notes:
      1. To create a scrapbook: From the menu bar, select File > New > Other. Then select Java > Java Run/Debug > Scrapbook Page. Then click Next.
    55. Old Notes on taking the Java Exam
Go to Home page. Kindly report errors, typos, or misspellings here.