Java

Topic: Packages

How to use package?

 	IntroductionMany times when we get a chance to work on a small project, one thing we intend to do is to put all java files into one single directory. It is quick, easy and harmless. However if our small project gets bigger, and the number of files is increasing, putting all these files into the same directory would be a nightmare for us. In java we can avoid this sort of problem by using Packages.Packages are nothing more than the way we organize files into different directories according to their functionality, usability as well as category they should belong to. An obvious example of packaging is the JDK package from SUN (java.xxx.yyy) as shown below:Figure 1. Basic structure of JDK packageBasically, files in one directory (or package) would have different functionality from those of another directory. For example, files in java.io package do something related to I/O, but files in java.net package give us the way to deal with the Network. In GUI applications, it's quite common for us to see a directory with a name "ui" (user interface), meaning that this directory keeps files related to the presentation part of the application. On the other hand, we would see a directory called "engine", which stores all files related to the core functionality of the application instead.Packaging also help us to avoid class name collision when we use the same class name as that of others. For example, if we have a class name called "Vector", its name would crash with the Vector class from JDK. However, this never happens because JDK use java.util as a package name for the Vector class (java.util.Vector). So our Vector class can be named as "Vector" or we can put it into another package like com.mycompany.Vector without fighting with anyone. The benefits of using package reflect the ease of maintenance, organization, and increase collaboration among developers. Understanding the concept of package will also help us manage and use files stored in jar files in more efficient ways.How to create a packageSuppose we have a file called HelloWorld.java, and we want to put this file in a package world. First thing we have to do is to specify the keyword package with the name of the package we want to use (world in our case) on top of our source file, before the code that defines the real classes in the package, as shown in our HelloWorld class below:    // only comment can be here    package world;    public class HelloWorld {      public static void main(String[] args) {        System.out.println("Hello World");      }    }One thing you must do after creating a package for the class is to create nested subdirectories to represent package hierachy of the class. In our case, we have the world package, which requires only one directory. So, we create a directory world and put our HelloWorld.java into it.Figure 2. HelloWorld in world package (C:\world\HelloWorld.java)That's it!!! Right now we have HelloWorld class inside world package. Next, we have to introduce the world package into our CLASSPATH.Setting up the CLASSPATHFrom figure 2 we put the package world under C:. So we just set our CLASSPATH as:    set CLASSPATH=.;C:\;We set the CLASSPATH to point to 2 places, . (dot) and C:\ directory.Note: If you used to play around with DOS or UNIX, you may be familiar with . (dot) and .. (dot dot). We use . as an alias for the current directory and .. for the parent directory. In our CLASSPATH we include this . for convenient reason. Java will find our class file not only from C: directory but from the current directory as well. Also, we use ; (semicolon) to separate the directory location in case we keep class files in many places.When compiling HelloWorld class, we just go to the world directory and type the command:    C:\world\javac HelloWorld.javaIf you try to run this HelloWorld using java HelloWorld, you will get the following error:    C:\world>java HelloWorld    Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name:     world/HelloWorld)            at java.lang.ClassLoader.defineClass0(Native Method)            at java.lang.ClassLoader.defineClass(ClassLoader.java:442)            at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:101)            at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)            at java.net.URLClassLoader.access$1(URLClassLoader.java:216)            at java.net.URLClassLoader$1.run(URLClassLoader.java:197)            at java.security.AccessController.doPrivileged(Native Method)            at java.net.URLClassLoader.findClass(URLClassLoader.java:191)            at java.lang.ClassLoader.loadClass(ClassLoader.java:290)            at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)            at java.lang.ClassLoader.loadClass(ClassLoader.java:247)The reason is right now the HelloWorld class belongs to the package world. If we want to run it, we have to tell JVM about its fully-qualified class name (world.HelloWorld) instead of its plain class name (HelloWorld).    C:\world>java world.HelloWorld    C:\world>Hello WorldNote: fully-qualified class name is the name of the java class that includes its package nameTo make this example more understandable, let's put the HelloWorld class along with its package (world) be under C:\myclasses directory instead. The new location of our HelloWorld should be as shown in Figure 3:Figure 3. HelloWorld class (in world package) under myclasses directoryWe just changed the location of the package from C:\world\HelloWorld.java to C:\myclasses\world\HelloWorld.java. Our CLASSPATH then needs to be changed to point to the new location of the package world accordingly.    set CLASSPATH=.;C:\myclasses;Thus, Java will look for java classes from the current directory and C:\myclasses directory instead.Someone may ask "Do we have to run the HelloWorld at the directory that we store its class file everytime?". The answer is NO. We can run the HelloWorld from anywhere as long as we still include the package world in the CLASSPATH. For example,    C:\>set CLASSPATH=.;C:\;    C:\>set CLASSPATH // see what we have in CLSSPATH    CLASSPATH=.;C:\;    C:\>cd world    C:\world>java world.HelloWorld    Hello World    C:\world>cd ..    C:\>java world.HelloWorld    Hello WorldSubpackage (package inside another package)Assume we have another file called HelloMoon.java. We want to store it in a subpackage "moon", which stays inside package world. The HelloMoon class should look something like this:    package world.moon;    public class HelloMoon {      private String holeName = "rabbit hole";            public getHoleName() {        return hole;      }            public setHole(String holeName) {        this.holeName = holeName;      }    }If we store the package world under C: as before, the HelloMoon.java would be c:\world\moon\HelloMoon.java as shown in Figure 4 below:Figure 4. HelloMoon in world.moon packageAlthough we add a subpackage under package world, we still don't have to change anything in our CLASSPATH. However, when we want to reference to the HelloMoon class, we have to use world.moon.HelloMoon as its fully-qualified class name.How to use packageThere are 2 ways in order to use the public classes stored in package.1. Declare the fully-qualified class name. For example,    ...    world.HelloWorld helloWorld = new world.HelloWorld();    world.moon.HelloMoon helloMoon = new world.moon.HelloMoon();    String holeName = helloMoon.getHoleName();    ...2) Use an "import" keyword:    import world.*;  // we can call any public classes inside the world package     import world.moon.*;  // we can call any public classes inside the world.moon package    import java.util.*;  // import all public classes from java.util package    import java.util.Hashtable;  // import only Hashtable class (not all classes in java.util package)

Browse random answers:

Which package is always imported by default?
Does importing a package imports the sub packages as well? E.g. Does importing com.bob.* also import com.bob.code.*?
What is a Java package and how is it used?
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.BOB compile?
How to create a package
What is Subpackage (package inside another package) ?
How to use package?
How to Use classes stored in jar file?
How the Java Compiler Finds Files?
Write Example for package?
Explain the Directory Structure  of Packages?
Explain Package java.rmi.server?
Is the API for accessing and processing data stored in a data source (usually a relational database) using the JavaTM programming language.?
Explain Package java.util?
Explain Package javax.accessibility?
Explain Package javax.imageio?
Explain Package javax.imageio.plugins.jpeg?
Explain Package javax.jws.soap?
Explain about comparator in java.util package?
Explain Package javax.naming?
Explain about Enumeration<E> in java.util package?
Explain Package javax.rmi.CORBA?
Explain about EventListener interface?
Explain Package javax.rmi.CORBA?
Explain about Formattable in java.util package?
Explain Package javax.sql.rowset?
Explain Iterator<E> in java.util package?
Explain Package javax.swing?
Explain List<E> in java.util package?
Explain Package javax.xml?
Explain ListIterator<E> in java.util.package?
Explain Package javax.xml.bind.annotation.adapters?
Explain Map<K,V> in java.util.package?
Explain Package org.omg.CosNaming.NamingContextExtPackage?
Explain Map.Entry<K,V> in java.util package?
Explain Package org.omg.Messaging?
Explain Observer in java.util package?
Explain Package org.w3c.dom.events?
Explain Queue<E> in java.util package?
Explain RandomAccess in java.util package?
Explain SortedMap<K,V> in java.util package?
What is SortedSet?
What is public abstract class AbstractCollection<E>extends Objectimplements Collection<E>?
Explain about iterator?
Explain about size in java.util packages?
Explain isEmpty method?
Explain is contains?  
Explain method toArray?
Explain method toArray?
Explain method add?
What is remove in java.util package?
Explain method containsAll?
What is addAll?
Explain method removeAll?
Explain method retainAll ?
Explain method clear
Explain method toString
Explain java.utilClass AbstractQueue<E>?
Explain public boolean add(E o)?
Explain method removepublic E remove()?
Explain method element?
Explain method clearpublic void clear()?
Explain method addAll?
Explain  java.utilClass AbstractSequentialList<E>java.lang.Object
Explain method getpublic E get(int index)?
Explain  setpublic E set(int index,             E element)?
Explain method listIteratorpublic abstract ListIterator<E> listIterator(int index)?
Explain method trimToSize?
Explain method ensureCapacity?
Explain method isEmptypublic boolean isEmpty()
Explain method  indexOfpublic int indexOf(Object elem)?
Explain method  lastIndexOfpublic int lastIndexOf(Object elem)?
Explain method removeRangeprotected void removeRange(int fromIndex,                           int toIndex)?
Explain method sortpublic static void sort(long[] a)
Explain public static void sort(Object[] a)?
Explain method binarySearchpublic static int binarySearch(long[] a,                               long key)?
Explain method equalspublic static boolean equals(long[] a,                             long[] a2)?
Explain method fillpublic static void fill(long[] a,                        long val)?
Explain method getAnnotation(Class<A> annotationClass) in java?
Explain method asListpublic static <T> List<T> asList(T... a)?
Explain method getAnnotations() in java?
Explain hashCodepublic static int hashCode(long[] a)?
Explain method getDeclaredAnnotations() in java ?
Explain method getImplementationTitle() in java  ?
Explain method getImplementationVendor() in java?
Explain  method getImplementationVersion() in java ?
Explain method deepHashCodepublic static int deepHashCode(Object[] a)
Explain method getName() in java?
Explain method deepEqualspublic static boolean deepEquals(Object[] a1,                                 Object[] a2)
Explain method getPackage(String name)  in java?
Explain method toStringpublic static String toString(long[] a)
Explain method getPackages() in java?
Explain method getSpecificationTitle() in java?
Explain method getSpecificationVendor() ?
Explain method getSpecificationVersion() in java ?
Explain method deepToStringpublic static String deepToString(Object[] a)
Explain method hashCode() in java ?
Explain method isAnnotationPresent(Class<? extends Annotation> annotationClass)  in java?
Explain method isCompatibleWith(String desired) in java?
Explain method isSealed() in java?