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) {
using the following command:
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$ at Method) at at java.lang.ClassLoader.loadClass( at sun.misc.Launcher$AppClassLoader.loadClass( at java.lang.ClassLoader.loadClass( 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:
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.