Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I run my java Hello World program if it is inside a package?

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?

like image 677
Matthew Avatar asked Jun 21 '10 01:06

Matthew


People also ask

Which command will run the compiled Hello Java file?

Compile it by typing “javac HelloWorld. java” in the terminal window. Execute (or run) it by typing “java HelloWorld” in the terminal window.

How do you do Hello World in Java?

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.

How do you start a program in Java?

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.


1 Answers

Now that it's in testpackage, its name is really testpackage.Hello. So go up a directory and do java on that.

like image 186
amara Avatar answered Oct 02 '22 20:10

amara