DOC

Introduction to Java programming

By Leslie Black,2014-04-24 11:34
12 views 0
Introduction to Java programming

1 THE “java.util” PACKAGE

    The standard utilities package in Java offers a great number of very useful general-purpose classes. Various container classes offer standard ways of handling linked lists, hashtables and bit sets. Other classes handle text parsing and date/calendar handling. 1.1 Vector

    Vector is the most used class of the java.util package. It is a linked list of objects, which is implemented in a very efficient way. The main advantage of a Vector is that (as all linked lists) there is no pre-defined size for it, so the only size limit comes from the available quantity of computer memory. Example 1 shows how a Vector is used for storing any number of names entered by the user.

    Example 1. Using Vector (compiled and run).

    import java.util.Vector;

    import java.io.*;

public class VectorExample

    {

     public static void main(String[] args)

     {

     String name;

     Vector names = new Vector();

     try {

     BufferedReader stdin =

     new BufferedReader(new InputStreamReader(System.in));

     System.out.println("Enter names:");

     do {

     name = stdin.readLine();

     if ( name.length() != 0 ) names.addElement(name);

     } while ( name.length() != 0 );

     stdin.close();

     }

     catch ( IOException e ) {}

     for ( int i = 0 ; i < names.size() ; i++ )

     System.out.println((String) names.elementAt(i));

     }

    }

Program run:

Enter names:

    john

    elvis

    edmond

    Gary Glitter

    Suzi Quattro

john

    elvis

    edmond

    Gary Glitter

    Suzi Quattro

Vectors store any kind of object, so the method "addElement()" takes an "Object" as

    parameter and "elementAt()" returns a reference to an "Object". This means that it is up

    to the programmer to know (or to test) what is the real class of the objects stored in the Vector. In the example, we know that all objects stored are of class String, so we can directly type cast all objects that are retrieved from the Vector to String objects. Then again, in the example there is no need to do a type cast in the call to "System.out.println()" since all Java

    objects have a "toString()" method.

    1.2 Enumeration

    Enumeration is a convenience interface for stepping through all the elements of a container like a Vector. In Example 1 the contents of the Vector could also have been written out by the following loop:

    for (Enumeration e = names.elements() ; e.hasMoreElements() ; )

     System.out.println(e.nextElement());

    The usefulness of the Enumeration interface is not that obvious for a Vector. However, for some other container classes it is very convenient. In cases where several different container classes are used, Enumeration also offers a common way for accessing them all. 1.3 Stack

    Stack implements a standard LIFO (Last In First Out) for storing objects of any class. It is a derived class from Vector, so there is no storage capacity limit, except the quantity of computer memory.

    1.4 BitSet

    Bit sets are used for storing true/false information. Java contains bit manipulation operators, but these are useful only for small bitmaps, which have a pre-defined size.

    Objects of class BitSet only use one bit per information and only reserve as much memory as necessary.

    Example 2 shows how to check which characters are present in a string. The BitSet initially uses no memory. Each time the "set()" method is called, memory gets allocated if needed

    for storing the new value.

    Example 2. Using the BitSet class (compiled and run).

    import java.util.*;

public class BitSetExample

    {

     private BitSet used = new BitSet();

     public static void main(String[] argv)

     {

     System.out.println(new BitSetExample(

    "Advanced Java Programming Course!"));

     }

     public BitSetExample(String str)

     {

     for ( int i = 0 ; i < str.length() ; i++ )

     // Set the bit for the character.

     used.set(str.charAt(i));

     }

     public String toString()

     {

     String desc = "[";

     int size = used.size();

     for ( int i = 0 ; i < size ; i++ ) {

     if ( used.get(i) )

     desc += (char) i;

     }

     return desc + "]";

     }

    }

Program run:

    C:\Examples>java BitSetExample

    [ !ACJPacdegimnorsuv]

1.5 Dictionary, Hashtable and Properties

    Dictionary is an abstract class that is the base class for Hashtable. Hashtables are used for storing key/value pairs, where the values can be retrieved very rapidly when the key is known. For instance, if we have a stock database with date/price pairs, then we could use the dates as keys for rapidly retrieving the corresponding stock price. A Hashtable is much faster for this than sequential search in a table, for instance.

"Properties" is a derived class from Hashtable. It offers convenience methods for using

    String objects both as keys and as values. It is also possible to save and load Properties objects to/from a file.

    1.6 Observer/Observable

    Observer is an interface which should be implemented by classes that want to be notified of changes in other objects that are of class Observable.

    An example of an application where this is useful is when clicking one button should cause several different windows to update their contents.

    Asynchronous image loading is a special case of Observer/Observable. The classes ImageProducer, ImageObserver and ImageConsumer are used in that case. Their purpose is to notify interested objects about the current image loading state, so that images may be displayed incrementally.

    1.7 StringTokenizer

    StringTokenizer is a class that implements the Enumeration interface. It is used for parsing text strings that contain certain token delimiters.

    Normal space characters (space, tab, newline) are the default delimiters, but it is possible to define any set of delimiters.

    Example 3 shows how to retrieve the words in a text string using the standard delimiter set. Example 3. Parsing a text into words (compiled and run).

    import java.util.StringTokenizer;

public class StringTokenizerExample

    {

     public static void main(String[] args)

     {

     StringTokenizer st = new StringTokenizer(args[0]);

     while (st.hasMoreTokens()) {

     System.out.println(st.nextToken());

     }

     }

    }

Program run:

    C:\Examples>java StringTokenizerExample "Hello world and the rest too" Hello

    world

    and

    the

    rest

    too

1.8 Date and Calendar

    Date and Calendar are classes for treating time and date related information. Most methods of the Date class are deprecated since they do not treat locale-specific settings

    properly. This is why Date objects are mainly used for storing the date information itself, with

    methods of other classes operating on them.

    As shown by Example 4, the classes "DateFormat" and "Calendar" are the ones whose

    methods should be used.

    Example 4. Using Date, DateFormat and Calendar classes (compiled and run). import java.util.*;

    import java.text.*;

public class DateExample

    {

     public static void main(String[] argv)

     {

     try {

     Date d = DateFormat.getDateInstance().parse(argv[0]);

     System.out.println(d);

     Calendar c = Calendar.getInstance();

     c.setTime(d);

     c.add(Calendar.DATE, 55);

     System.out.println(c.getTime());

     }

     catch ( java.text.ParseException e ) {

     System.out.println(e);

     }

     }

    }

Program run:

    C:\Examples>java DateExample 5.5.1999

    Wed May 05 00:00:00 GMT+03:00 1999

    Tue Jun 29 00:00:00 GMT+03:00 1999

This example works under Windows 98 configured with Finnish settings. If we want to use

    some other separating character than '.', like '/' for instance, then the first line after the "try"

    statement should look like this:

Date d = new SimpleDateFormat("dd/mm/yyyy").parse(argv[0]);

    This means that we define a new time pattern for parsing the date. Now the program could be run like this:

    C:\Examples>java DateExample 5/5/1999

    Tue Jan 05 00:05:00 GMT+02:00 1999

    Mon Mar 01 00:05:00 GMT+02:00 1999

    Parsing date information is quite a problematic task due to the various conventions used in different countries. Therefore great care should be taken when retrieving date information from files or databases.

    1.9 Random

    Pseudo-random number generator containing methods for getting int, long, float or double random numbers. The static method "random()" of the class "java.lang.Math" may

    also be used for this purpose.

Report this document

For any questions or suggestions please email
cust-service@docsford.com