Thursday, July 15, 2010

Java Classpath

The classpath in Java defines which java class are available.

For example if you want to use an external Java library you have to add this library to your classpath to use it in your your program.

Your first Java program

// The smallest Java program possible

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hi java..");
}
}
Compile the code

directory structure


c:\temp\java\HelloWorld.java .

c:\temp\java\javac Helloworld.java

c:\temp\java\java Helloworld

Now is working fine..

classpath setting and run the code in different directory

Check the content of the directory with the command "dir". The directory contains now a file "HelloWorld.class".

Start-> Run -> cmd

c:\>java HelloWorld

now: we will get this error message:

If you are not in the directory in which the compiled class is stored then the system should result an error message Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass

how to solve this problem using Classpath

c:\> java -classpath "mydirectory" HelloWorld . Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.

C:\>java -classpath C:\temp\java HelloWorld

No comments:

Post a Comment