0

I have java file HelloWorld.java with the following code:

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

Now my understanding is, to compile and run this we need two steps: Step 1)javac HelloWorld.java Step 2)java HelloWorld. So clearly the command java takes the class file name as its input parameter.

However if I do java HelloWorld.java, it prints the output of the program despite the fact that I have passed the java filename and not the class name to it. See the screenshot below.

enter image description here

Can someone clarify this please?

Java - openjdk version "11.0.8" 2020-07-14 LTS(AWS Corretto)

OS - Amazon Linux 2(red hat based OS)

Infra - AWS EC2 instance

Edit: Also I noticed this happens only if the corresponding classfile is not there in the directory. If the corresponding classfile is there, it takes gives the error: error: class found on application class path: HelloWorld

DockYard
  • 989
  • 2
  • 12
  • 29

2 Answers2

4

This was introduced in java 11.

If you have installed a JDK, you can call javac directly using the source file.

java <Class>.java

is basically the same as

javac <Class>.java
java <Class>
dan1st
  • 12,568
  • 8
  • 34
  • 67
2

This was a new feature introduced in Java 11 to enhance the java launcher to run a program supplied as a single file of Java source code. For more info you can visit the link JEP 330

Vipul Kumar
  • 423
  • 4
  • 11