Cody
Cody

Reputation: 2649

Getting NoClassDefFoundError in Java

I am learning about classpath in java. I created a package called Geometry which is stored in C:\Java\ containing one file Point.java which contains the following code

package Geometry;

public class Point 
{
    double x;
    double y;

    public Point(double xVal, double yVal) 
    {
        x = xVal;
        y = yVal;
    }

    public Point(final Point oldPoint) 
    {
        x = oldPoint.x;
        y = oldPoint.y;
    }

    void move(double xDelta, double yDelta)
    {
        x += xDelta;
        y += yDelta;
    }

    double distance(final Point aPoint)
    {
        return Math.sqrt(  Math.pow((x - aPoint.x), 2) + Math.pow((y - aPoint.y), 2)  );
    }

    public String toString()
    {
        return x + ", " + y;
    }

}

Then i created another file in C:\Users\username\workspace\Test called Test.java

Which contains the following

import Geometry.*;

public class Test 
{
    public static void main(String[] args) 
    {       
        Point l1 = new Point(1,2,3,4);
        System.out.println(l1);
    }

}

Then compiling using

C:\Users\username\workspace\Test>javac -cp c:\Java Test.java

It compiles successfully but throwing NoClassDefFoundError exception error in run time. What is the problem

Upvotes: 0

Views: 133

Answers (1)

JP Moresmau
JP Moresmau

Reputation: 7403

(Answer given in comments by JP Moresmau and RC, putting it here for completion).

In Java, you need to specify a classpath both when compiling and when running. So when you compile with

javac -cp c:\Java Test.java

You're compiling the Test class in the current directory, using c:\Java as an EXTRA classpath parameter.

When you want to run the Test class, you need to tell Java where to find its own class (in the current directory) but also the required classes. If you just run

java Test

Java will use the current folder as the only classpath, and hence won't find the class referenced, that have been compiled in C:\Java. Hence you need to specify

java -cp "C:\Java;." Test

To indicate where to find all required classes.

Upvotes: 1

Related Questions