I created a file called "Hello.java" that looks like this:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
I ran javac Hello.java
, then java Hello
, and everything worked as expected.
I then added the line package testpackage;
to the top of the file, and put it in the directory /home/matthew/Desktop/hellotest/testpackage
. I put .:/home/matthew/Desktop/hellotest
in my CLASSPATH, and compiled and ran the same way as before. But now, I get this error:
matthew@matthew-laptop:~/Desktop/hellotest/testpackage$ java Hello
Exception in thread "main" java.lang.NoClassDefFoundError: Hello (wrong name: testpackage/Hello)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:334)
Could not find the main class: Hello. Program will exit.
Why did it work on its own, but not in a package?
Compile it by typing “javac HelloWorld. java” in the terminal window. Execute (or run) it by typing “java HelloWorld” in the terminal window.
The signature of the main method in Java is: public static void main(String[] args) { ... .. ... } System.out.println("Hello, World!"); The code above is a print statement.
Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.
Now that it's in testpackage
, its name is really testpackage.Hello
. So go up a directory and do java
on that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With