在过去,我一直使用c++作为编程语言。我知道用c++写的代码要经过一个编译过程,直到它成为目标代码“机器代码”。

我想知道Java在这方面是如何工作的。用户编写的Java代码是如何被计算机运行的?


当前回答

Java被编译成字节码,然后进入Java VM,由其解释。

其他回答

两者都有。首先,java编译(有些人更喜欢说“翻译”)字节码,然后根据JIT的情绪进行编译或解释。

术语“解释语言”或“编译语言”没有意义,因为任何编程语言都可以解释和/或编译。

对于Java的现有实现,大多数都涉及到字节码的编译步骤,因此它们涉及到编译。运行时还可以动态加载字节码,因此总是需要某种形式的字节码解释器。 该解释器可能会也可能不会在内部使用对本机代码的编译。

如今,部分即时编译被用于许多曾经被认为是“解释型”的语言,例如JavaScript。

报价来自:https://blogs.oracle.com/ask-arun/entry/run_your_java_applications_faster

Application developers can develop the application code on any of the various OS that are available in the market today. Java language is agnostic at this stage to the OS. The brilliant source code written by the Java Application developer now gets compiled to Java Byte code which in the Java terminology is referred to as Client Side compilation. This compilation to Java Byte code is what enables Java developers to ‘write once’. Java Byte code can run on any compatible OS and server, hence making the source code agnostic of OS/Server. Post Java Byte code creation, the interaction between the Java application and the underlying OS/Server is more intimate. The journey continues - The enterprise applications framework executes these Java Byte codes in a run time environment which is known as Java Virtual Machine (JVM) or Java Runtime Environment (JRE). The JVM has close ties to the underlying OS and Hardware because it leverages resources offered by the OS and the Server. Java Byte code is now compiled to a machine language executable code which is platform specific. This is referred to as Server side compilation.

所以我认为Java绝对是一种编译语言。

Java被编译成字节码,然后进入Java VM,由其解释。

Java实现通常使用两步编译过程。Java源代码由Java编译器编译成字节码。字节码由Java虚拟机(JVM)执行。现代jvm使用一种称为即时(JIT)编译的技术,在运行时将字节码编译为硬件CPU能够理解的本机指令。

JVM的一些实现可能会选择解释字节码,而不是JIT将其编译为机器码,然后直接运行它。虽然这仍然被认为是一个“解释器”,但它与读取和执行高级源代码的解释器有很大的不同(即,在这种情况下,Java源代码不直接解释,字节码,Java编译器的输出,被直接解释)。

从技术上讲,可以提前将Java编译成本机代码并运行生成的二进制代码。也可以直接解释Java代码。

总之,根据执行环境的不同,字节码可以是:

提前编译并作为本地代码执行(类似于大多数c++编译器) 及时编译并执行 解释 由受支持的处理器直接执行(字节码是某些cpu的本机指令集)