Packages (Cont.)


Importing a Package
There are many packages to choose from. In the previous example, we used the ArrayList class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes. To import a whole package, end the sentence with an asterisk sign (*).

The example will import ALL the classes in the java.util package:
import java.util.*;

User-Defined Packages
To create your own package, you need to understand that Java uses a file system directory to store them.

Just like folders on your computer: To create a package, use the package keyword:
└── root
  └── mypack
    └── MyPackageClass.java

MyPackageClass.java (a user-defined package example)
package mypack;
class MyPackageClass {
  public static void main( String[ ] args ) {
    System.out.println( "This is my package!" );
  }
}
undcemcs02.und.edu (a use scenario)
undcemcs02> # Create the file. 
undcemcs02> emacs MyPackageClass.java

undcemcs02> # List the file contents.
undcemcs02> cat MyPackageClass.java
package mypack;
class MyPackageClass {
  public static void main( String[ ] args ) {
    System.out.println( "This is my package!" );
  }
}
undcemcs02> # Compile the file.
undcemcs02> javac MyPackageClass.java

undcemcs02> # Compile the packages.
undcemcs02> javac -d . MyPackageClass.java

undcemcs02> # This forces the compiler to create the "mypack" package.

undcemcs02> # The -d keyword specifies the destination for where to
undcemcs02> # save the class file.
undcemcs02> # You can use any directory name, like c:/user (windows), or
undcemcs02> # if you want to keep the package within the same directory,
undcemcs02> # you can use the dot sign ".", like in the example above.
undcemcs02> # Note: The package name should be written in lower case to
undcemcs02> # avoid conflict with class names.

undcemcs02> ls 
mypack/     MyPackageClass.class      MyPackageClass.java

undcemcs02> ls mypack/
MyPackageClass.class

undcemcs02> # When we compiled the package in the example above, a new
undcemcs02> # folder was created, called "mypack".
undcemcs02> # To run the MyPackageClass.java file, write the following:
undcemcs02> java mypack/MyPackageClass
This is my package!
shell> java mypack/MyPackageClass

      Output:




      Two hunters are out in the woods when one of them collapses.    
      He’s not breathing and his eyes are glazed.    
      The other guy whips out his cell phone and calls 911.    
      “I think my friend is dead!” he yells. “What can I do?”    
      The operator says, “Calm down. First, let’s make sure he’s dead.”    
      There’s a silence, then a shot.    
      Back on the phone, the guy says, “OK, now what?”