08. Java Packages

Library PackagesA package is a group of related .class files in the same directory/subdirectory (folder).

Java Library Packages:

Are described on the internet at: http://docs.oracle.com/javase/7/docs/api/

Some of the Java Packages:

  • java.applet - contains classes for supporting applets
  • java.awt - contains classes for "heavyweight" graphical user interface components
  • java.awt.event - contains classes for event handling
  • java.io - contains classes for input and output streams
  • java.lang - contains core (default) Java classes (see following pages)
  • java.net - contains classes for network communications
  • java.text - contains classes for formatting, including styles
  • java.util - contains classes for utilities (date, vectors, etc.)
  • javax.swing - contains classes for "lightweight" graphical user interface components

java.lang Package

  • The java.lang package contains the classes that are essential to the Java language
  • java.lang is implicitly imported, so you don't have to import it
  • Contains the Object class (ancestor of all classes) and the Class class
  • Contains "wrapper" classes Boolean,Character, Byte, Short, Integer, Long,Float and Double
  • Contains String and StringBuffer classes
  • Contains Runtime and System* classes, which provide low-level (platform-dependent) methods. Some of the Runtime methods are called via the System methods.
  • Contains the Math class, which contains only class (static) variables and class (static) methods
  • Contains the Thread class andThrowable class (discussed later in the quarter)
  • Contains Exception and Error classes, which are the superclasses of all exceptions and errors

Creating a Package

  • If using an IDE like NetBeans or Eclipse, follow the directions for creating a package for your IDE (for example, File->New->Package in Eclipse, or look up in your IDE). However, if you're not using an IDE, you'll need to do the following:
  • Put a package statement at the top (must be the FIRST non-comment line of the file) of the source file in which the class or interface is defined
  • Syntax: package pkg-name-from-classpath;

NOTE: the classpath for your non-Java library packages could be any subdirectory that you would set.

For example, in the source file Circle.java:

package graphics;

public class Circle {

. . .

}

  • The top of every source file that defines a class or interface that is to be a member of a package must include a package statement
  • If you do not use a package statement, your class or interface ends up in the default package, which is a package that has no name. Usually, the default package is only for small or temporary applications or when you are just beginning development. Otherwise, classes and interfaces belong in named packages.
  • Recall: When no access specifier is given for a class, method or variable, then it can only be accessed by all methods in the same package.

Naming of packages convention:

  • The compiler allows two classes to have the same name when they are in different packages
  • Companies use their reversed Internet domain name in their package names, like this: com.company.package. (Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or project name after the company name, for example, com.company.region.package.)

Managing and Using Packages

Managing Source and Class Files:

  • Put the source files (.java files) in a directory whose name reflects the name of the package to which the class or interface belongs. For example, Circle.java would be in a directory named graphics, which may be anywhere on the file system.
  • The long name of the package member and the pathname to the file are parallel (assuming the UNIX filename separator slash / ), for example:

graphics.Circle class name

graphics/Circle.java pathname to file

  • Compile the source files so that the .class files are also be in a series of directories that reflect the package name, which usually is NOT the same directory as its source. For example (in DOS/Windows):

c:\sources\graphics\Circle.java

c:\classes\graphics\Circle.class

Using Package Members:

In your source code, to use a public package (MUST be public) member from outside its package, you must either

  • refer to the member by its long (disambiguated) name,

graphics.Circle myRect = new graphics.Circle();

  • import the package member, so you could refer to the class with its short name (e.g., Circle)

import graphics.Circle;

  • import the member's entire package.

import graphics.*;

Now you can refer to any class or interface in the graphics package by its short name

  • The asterisk (*) in the import statement can be used only to specify all of the classes within a package, as shown on the previous page. It cannot be used to match a subset of the classes in a package.

If by some chance a member in one package shares the same name with a member in another package and both packages are imported, you must refer to the member by its long name.

Try Packages

NOTE: If you're not using an IDE, you will need to set your class path See http://download.oracle.com/javase/1.3/docs/tooldocs/win32/classpath.html for information on how to set your classpath.

More on the System Class

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined "properties"; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

System static variables:

in

  • Declared: public static final InputStreamin
  • The "standard" input stream. This stream is already open and ready to supply input data.
  • Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.

out

  • Declared: public static final PrintStreamout
  • The "standard" output stream. This stream is already open and ready to accept output data.
  • Typically this stream corresponds to display output or another output destination specified by the host environment or user.

Examples of usage:

public static String getString(){
  StringBuffer sb = new StringBuffer(80);
  int inum;
  try {
          while( (inum =System.in.read()) != -1 ){
              char ch = (char) inum;
              if( ch == '\n' ) break;
              sb.append(ch);
          } // end while
          System.out.println(sb);
  }catch( IOException e ){
          System.out.println(e);
       } // end catch
  return sb.toString();
} // end getString method

System Class Methods

(only a few mentioned here):

public static long currentTimeMillis()

  • Returns the current time in milliseconds.
  • See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).
  • Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

public static void arraycopy( Object src, int src_position, Object dst,int dst_position, int length)

  • Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.
  • A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dst.
  • The number of components copied is equal to the length argument.
  • The components at positions srcOffset through srcOffset+length-1 in the source array are copied into positionsdstOffset through dstOffset+length-1, respectively, of the destination array.

public static void exit(int status)

  • Terminates the currently running Java Virtual Machine.
  • The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
  • This method calls the exit method in class Runtime. This method never returns normally.
  • Parameters: status - exit status.
  • Throws: SecurityException - if a security manager exists and its checkExit method doesn't allow exit with the specified status.

public static void gc()

  • Runs the garbage collector.
  • Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

public static void runFinalization()

  • Runs the finalize* methods of any objects pending finalization. (*see below about finalize)
  • Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.
  • finalize method is invoked before the garbage collector "collects" this object and is used to "clean up" the object (e.g., close files or databases). This method must be protected.