Reputation: 39
I wrote this code in file named Hello.java
public class Hello{
System.out.println("Hello there");
}
then I wrote command javac hello.java
and java hello
and prints successfully
However if I make changes to the code and write
public class Demo{
System.out.println("New hello");
}
and run command java hello.java
This also works and prints successfully. However I am not following any Java parameters(file name and class name should be same) for defining class name so why does this works?
I know I am doing the wrong way but if I didn't follow the pattern it shouldn't execute, right ?!
and if I knowingly make semicolon mistake and run the command java hello.java
it says compilation failed, but isn't the task of compilation complete ?
Upvotes: 0
Views: 62
Reputation: 18418
What you've encountered here is a "source-file" mode of java launcher: Java launcher has 4 launching modes:
We are talking about fourth option here:
In source-file mode, the effect is as if the source file is compiled into memory, and the first class found in the source file is executed. For example, if a file called HelloWorld.java contains a class called hello.World, then the command
java HelloWorld.java
is informally equivalent to
javac -d <memory> HelloWorld.java
java -cp <memory> hello.World
The compiler does not enforce the optional restriction defined at the end of JLS §7.6, that a type in a named package should exist in a file whose name is composed from the type name followed by the .java extension.
For more info read the specification Jep 330.
Upvotes: 2