Why the Java language need bytecode? Why java design in this way? [closed]

China☆狼群 提交于 2019-12-17 19:50:53

问题


As I know a java developer, need to let their .java file to become .class, and the .class requires the JVM to convert to native code to execute. Why the Java design in this way? Why don't just as a scripting language, using a interpreter, to interpreter .java file? or why don't just convert it to executable like C? Why need to convert to bytecode? What is the design philosophy behind the java language?


回答1:


It is for sake of speed and portability at the same time.

All of what I am going to say is to be adapted and moderated depending on the case, but roughly:

  • If you merely interpret the java file with an interpreter you would have portability but not speed.

  • If you have to compile the code for a given processor architecture you would have speed but not portability.

  • With the bytecode, you compile the code (into bytecode) for a common machine that will execute it (the JVM) it is a compromise between speed and portability.




回答2:


Why the Java design in this way?

Write once, run everywhere - portability.

Why don't just as a scripting language, using a interpreter, to interpreter .java file?

Performance. Bytecode can be compiled to native code with some aggressive optimizations, not available for normal compilers.

or why don't just convert it to executable like C?

Because different platforms require different executable binaries. Java bytecode is (again) portable.




回答3:


Why don't just as a scripting language, using a interpreter, to interpreter .java file? or why don't just convert it to executable like C? Why need to convert to bytecode?

I think the intention was to have

1) Compile time safety
2) Write once, run anywhere.

If you converted to an executable like C, you would lose #2. In a sense, the JVM is an interpreter, so Java bytecode in interpreted, while Java code code is compiled.




回答4:


Why don't just as a scripting language, using a interpreter, to interpreter .java file?

Suit yourself.

or why don't just convert it to executable like C?

Because that won't work cross-platform. A Portable Executable (used on Windows) won't run on, say, Linux or iOS, at least not without tricks.

A simple comparison can be made by thinking of sockets and file access. How would you do that on different platforms, with one executable, without the JVM?




回答5:


  1. Interpreting (and compiling) byte code is faster than interpreting raw java.

  2. Byte code is portable. You can compile on Windows, and run the byte code on Mac or Unix.



来源:https://stackoverflow.com/questions/8153792/why-the-java-language-need-bytecode-why-java-design-in-this-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!