user2719875 user2719875 - 2 months ago 7
Java Question

Getting a java.lang.NoClassDefFoundError error even when .class file exists

This is my file structure:

T1 -> T1sample -> src -> t1sample -> T1.java
T1 -> T1sample -> src -> t1sample -> T1.class


I created these folders and files myself (except for T1.class, I got that by running 'javac T1.java' from the shell).

This is T1.java:

package t1sample;

public class T1 {
public static void main(String []args) {
System.out.println('Test');
}
}


Now when I try to run
java T1
it returns an error saying:

java.lang.NoClassDefFoundError: T1 (wrong name: t1sample/T1)


Any idea why?

Answer

First create the directory structure... (Using gvim as an editor)

~/Desktop $ mkdir -p T1sample/src/t1sample && cd T1sample/src/t1sample && gvim T1.java

Create the source...

package t1sample;

public class T1 {

    public static void main(String... args) {
        System.out.println("Test"); 
    }
}

Compile ...

~/Desktop $  cd T1sample/src/t1sample/
~/Desktop/T1sample/src/t1sample $  javac T1.java

Confirm...

~/Desktop/T1sample/src/t1sample $  ls -la
total 2
-rw-r--r-- 1 Edward None 411 Sep 28 21:46 T1.class
-rw-r--r-- 1 Edward None 137 Sep 28 21:45 T1.java

Run it...

~/Desktop/T1sample/src/t1sample $  cd ..
~/Desktop/T1sample/src $  java t1sample.T1
Test
Comments