I’m trying to learn how to make & use packages in Java. I’ve experimented with the following “Hello World” program
class helloWorld
{
public static void main (String[] args)
{
System.out.println("Hello World");
}
}
When I compile and run this program in it’s home directory everything is fine. However, when I create a sub-directory – ./testPackage and place the following file (hiEarth.java) in it:
package testPackage;
class hiEarth
{
public static void main (String[] args)
{
System.out.println("Hi Earth");
}
}
I can seemingly compile it, but can’t run it.
me@ubuntu:~/Projects/JavaProjects/helloWorld/testPackage$ javac hiEarth.java
me@ubuntu:~/Projects/JavaProjects/helloWorld/testPackage$ java hiEarth
Exception in thread "main" java.lang.NoClassDefFoundError: hiEarth (wrong name: testPackage/hiEarth)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: hiEarth. Program will exit.
when I do an ‘ls‘, I see what I expect to see:
me@ubuntu:~/Projects/JavaProjects/helloWorld/testPackage$ ls
hiEarth.class hiEarth.java
Why can’t I get java to see a class in the present directory?
When I move one directory above:
me@ubuntu:~/Projects/JavaProjects/helloWorld/testPackage$ cd ..
me@ubuntu:~/Projects/JavaProjects/helloWorld$ java testPackage/hiEarth
Things work fine. I thought this might be a classpath issue, but
me@ubuntu:~/Projects/JavaProjects/helloWorld/testPackage$ java -cp . hiEarth
doesn’t work either. What don’t I understand here?
Thanks….
Go to ~/Projects/JavaProjects/helloWorld/ and type
When you execute the java command, you need to provide the fully qualified name of the Java class you want to execute (ie, here, testPackage.hiEarth). The lookup of the classes will be relative to the directories and jars you provide in your classpath argument. Therefore, looking for testPackage.hiEarth will result in this case into ./testPackage/hiEarth.class which will work if relative to ~/Projects/JavaProjects/helloWorld/
NB: Use the Java naming convention and use a capital letter for your class.