英文:
Why is Java command working with java files as parameter
问题
以下是翻译好的部分:
我有一个名为HelloWorld.java
的Java文件,其中包含以下代码:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
现在我的理解是,要编译和运行这个程序,我们需要两个步骤:步骤1)javac HelloWorld.java
步骤2)java HelloWorld
。所以显然,java
命令以类文件名作为其输入参数。
然而,如果我执行java HelloWorld.java
,尽管我传递的是Java文件名而不是类名,它仍然会打印程序的输出,如下面的屏幕截图所示。
请问有人能够澄清这一点吗?
Java - openjdk版本 "11.0.8" 2020-07-14 LTS(AWS Corretto)
操作系统 - Amazon Linux 2(基于Red Hat的操作系统)
基础设施 - AWS EC2实例
编辑:我还注意到,只有在目录中不存在相应的类文件时才会发生这种情况。如果相应的类文件存在,它会报错:错误:在应用程序类路径上找到类:HelloWorld
。
英文:
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.
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
答案1
得分: 4
这是在Java 11中引入的。
如果你已经安装了JDK,你可以直接使用源文件来调用javac
。
java <Class>.java
基本上与
javac <Class>.java
java <Class>
相同。
英文:
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>
答案2
得分: 2
这是Java 11中引入的新功能,旨在增强Java启动器以运行作为单个Java源代码文件提供的程序。有关更多信息,您可以访问链接JEP 330。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论