I have got the following code in a file called test.java which is located inside the directory C:\D\JavaProjects
class test
{
public static void main( String[] str )
{
System.out.println( "Hello, World! from test" );
}
}
class Test
{
public static void main( String[] str )
{
System.out.println( "Hello, World!" );
}
}
When I do "javac test.java" it outputs test.class. Now, if I do "java test" I get the following output:
Exception in thread "main" java.lang.NoClassDefFoundError: test (wrong name: Test) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Could not find the main class: test. Program will exit.
But when I do "java Test" I get
Hello, World!
Now, if I simply reverse the occurrence of the two class declarations, such that Test is declared BEFORE test, the java compiler outputs the file Test.class. Now doing "java test" gives the output:
Hello, World! from test
but "java Test" gives
Exception in thread "main" java.lang.NoClassDefFoundError: Test (wrong name: test) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Could not find the main class: Test. Program will exit.
Now, I know it is very strange to have two classes with main in them in the same file, but this behavior seems completely illogical and more like a bug. Can somebody point me to the appropriate section of the Java Language Specification that specifies this behavior? Many thanks in advance for the help.