1

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?

enter image description here

Lars Gendner
  • 1,816
  • 2
  • 14
  • 24
soha
  • 115
  • 1
  • 12
  • 3
    possible duplicate of [executing java program from command line in windows fails](http://stackoverflow.com/questions/12773979/executing-java-program-from-command-line-in-windows-fails) – Mifeet Aug 29 '15 at 10:27
  • http://www.thejavageek.com/2013/07/21/using-javac-and-java-commands-to-compile-and-launch-java-programs/ – Prasad Kharkar Aug 29 '15 at 10:32

1 Answers1

0

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

Raja Anbazhagan
  • 4,092
  • 1
  • 44
  • 64