0

I am new to java..

I have an example structure as follows:

/folder/foo.java /folder/bar.java /folder/foobar.java

Now I am trying to run foobar.java but I get the following exception

Exception in thread "main" java.lang.ClassNotFoundException: /folder/foobar
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:247)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:149)

Then I tried to configure it by doing

java -classpath  .  foobar 
Exception in thread "main" java.lang.NoClassDefFoundError: foobar
Caused by: java.lang.ClassNotFoundException: foobar
    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:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)

Any clues? Thanks

1
  • 3
    looks like you need to compile foobar.java into foobar.class, via something like "javac foobar.java" Commented Dec 25, 2012 at 2:26

2 Answers 2

2

The default value of a classpath is ‘.’ , i.e. the current directory. The value of the classpath environment variable overrides this value. If the java command is issued with –cp or –classpath option, it overrides the default ‘.’ and classpath environment variable value.

Below is an example for setting a classpath during class execution C:>java -classpath "." com.abc.example.SayHello

As opposed to compiling where you need to give exact path, to run the class file, we need to follow the package structure.

This is due to the way the Classloader tries to resolve the class location by combining its package and class name. You must be on the package root location and issue the java command specifying the package structure.

C:>java com.abc.example.SayHello

Hello!!

Sign up to request clarification or add additional context in comments.

Comments

1

First, you need to compile java files:

javac /folder/*.java

Then you can run a class with main() function:

java -cp . folder.foobar

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.