字节码是源代码和机器码之间的中间代码。它是一种低级代码,是用高级语言编写的源代码编译的结果。它由像Java虚拟机 (JVM) 这样的虚拟机处理。
字节码在被解释器翻译成机器码之后是不可运行的代码,然后它才能被机器理解。它被编译为在 JVM 上运行,任何具有 JVM 的系统都可以运行它,而不管其操作系统如何。这就是Java独立于平台的原因。字节码被称为可移植码。
机器码:
机器代码是一组机器可直接理解的指令,由中央处理单元 (CPU) 处理。机器码采用二进制(0 和 1)格式,与字节码和源代码完全不同。它被认为是源代码的最底层表示。机器码是经过编译或解释后获得的。它也被称为机器语言。
下图说明了 Java源代码如何转换为字节码,然后再转换为机器码的示例:
字节码和机器码的区别:
S.NO. |
Byte Code |
Machine Code |
01. | Byte Code consisting of binary, hexadecimal, macro instructions like (new, add, swap, etc) and it is not directly understandable by the CPU. It is designed for efficient execution by software such as a virtual machine.intermediate-level | Machine code consisting of binary instructions that are directly understandable by the CPU. |
02. | Byte code is considered as the intermediate-level code. | Machine Code is considered as the low-level code. |
03. | Byte code is a non-runnable code generated after compilation of source code and it relies on an interpreter to get executed. | Machine code is a set of instructions in machine language or in binary format and it is directly executed by CPU. |
04. | Byte code is executed by the virtual machine then the Central Processing Unit. | Machine code is not executed by a virtual machine it is directly executed by CPU. |
05. | Byte code is less specific towards machine than the machine code. | Machine code is more specific towards machine than the byte code. |
06. | It is platform-independent as it is dependent on the virtual machine and the system having a virtual machine can be executed irrespective of the platform. | It is not platform independent because the object code of one platform can not be run on the same Operating System. Object varies depending upon system architecture and native instructions associated with the machine. |
07. | All the source code need not be converted into byte code for execution by CPU. Some source code written by any specific high-level language is converted into byte code then byte code to object code for execution by CPU. | All the source code must be converted into machine code before it is executed by the CPU. |