Friday, July 13, 2007

Java Package Tutorial

Java Package Tutorial (English version)

It took me 2 hours to get rid of the exceptions I got as the following. Just because I didn't use the fully-qualified class name.



Suppose we have a file called HelloWorld.java, and we want to put this file in a package 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.

Next, we have to introduce the world package into our CLASSPATH.

When compiling HelloWorld class, we just go to the world directory and type the command:

C:\world\javac HelloWorld.java


If 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


Note: fully-qualified class name is the name of the java class that includes its package name

No comments: