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

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


当前回答

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

其他回答

用Java编写的代码是:

首先由一个名为javac的程序编译为字节码,如上图左侧所示; 然后,如上图右侧所示,另一个名为java的程序启动java运行时环境,它可以使用java解释器/JIT编译器编译和/或解释字节码。


When does java interpret the bytecode and when does it compile it? The application code is initially interpreted, but the JVM monitors which sequences of bytecode are frequently executed and translates them to machine code for direct execution on the hardware. For bytecode which is executed only a few times, this saves the compilation time and reduces the initial latency; for frequently executed bytecode, JIT compilation is used to run at high speed, after an initial phase of slow interpretation. Additionally, since a program spends most time executing a minority of its code, the reduced compilation time is significant. Finally, during the initial code interpretation, execution statistics can be collected before compilation, which helps to perform better optimization.

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

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

Java是一种编译的编程语言,但它不是直接编译为可执行的机器代码,而是编译为一种称为JVM字节代码的中间二进制形式。然后对字节码进行编译和/或解释以运行程序。

报价来自: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绝对是一种编译语言。