简体   繁体   中英

How to compile and run a Java class (Hello World example)

I am new to Java. I wrote a simple program that prints "Hello World". My program compiled but did not run but gave me this exception:

Exception in thread main java.lang.NoClassDefFoundError:Hello wrong name : main hello

My program is like so:

package main;

public class Hello
{
    public static void main(String[] args)
    {
        System.out.println("Hello World");
    }
}

My program is in: \\main\\Hello.java I searched so much and compiled in different ways but i don't understand what the problem is. Can anyone help me?

在此处输入图片说明

You should have the Hello.java under main directory as per the package definition. So do the following.

d:>mkdir main
d:>move Hello.java main
d:>javac main\Hello.java
d:>java main.Hello

Which would print Hello World . This is because javac will output the .class file next to .java file by default.

If you don't want this behaviour or if you don't want to move the .java file, then you can also mention where the output classes needs to go.

d:>javac -d . Hello.java

This would create the Hello.class automatically under main directory as per the package definition in relevance to the current directory. Hence,

d:>java main.Hello

Which would also print Hello World

You can learn more about how to compile java source code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM