Showing posts with label classpath. Show all posts
Showing posts with label classpath. Show all posts

Saturday, January 15, 2011

How to run Java class file on Ubuntu

Let say you compile the following Java codes
public class hello {
    public static void main(String[] args) {
    System.out.println("rizauddin.com");
    }
}
using the following command:
javac hello.java
You will get a class file `hello.class`.

However, when you try to run the Java class file using
java hello

like you usually did on Windows, it won't run.
Exception in thread "main" java.lang.NoClassDefFoundError: hello Caused by: java.lang.ClassNotFoundException: hello at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) Could not find the main class: hello. Program will exit.
Actually, to run Java class file on Ubuntu, you need to always specify the classpath, using the `-cp` options.

As an example,
java -cp . hello

The `.` means the current working directory. In other words, you are telling Java to look for `hello class` in the same directory that you invoke the `java` command.

You can also add the current directory to the CLASSPATH, like this:
export CLASSPATH=.:$CLASSPATH
If you don't like to do that each time you want to run a Java class file, you can set the CLASSPATH permanently in /etc/environment or in ~/.profile.