i am new to java. i wanted to know this. what is the need to create the .class file in java ? can't we just pass the source code to every machine so that each machine can compile it according to the OS and the hardware ?
-
5Because compiling bytecode takes less time than compiling source code? Because bytecode is smaller than source code? – John Dvorak Dec 13 '14 at 07:12
-
Yeah, that's about the size of it. Good question, though. – Jon Kiparsky Dec 13 '14 at 07:15
-
Also because byte code isn't as easily viewable / modified by the end user. – Jonathon Reinhart Dec 13 '14 at 07:15
-
1Because the compiler is too big? Because developers don't want to open-source? – user4098326 Dec 13 '14 at 07:15
-
Even [Javascript is usually compiled to Javascript](http://closure-compiler.appspot.com/home) before being sent to the browser ;-) – John Dvorak Dec 13 '14 at 07:17
2 Answers
I believe it's mostly for efficiency reasons.
From wikipedia http://en.wikipedia.org/wiki/Bytecode:
Bytecode, also known as p-code (portable code), is a form of instruction set designed for efficient execution by a software interpreter. Unlike human-readable source code, bytecodes are compact numeric codes, constants, and references (normally numeric addresses) which encode the result of parsing and semantic analysis of things like type, scope, and nesting depths of program objects. They therefore allow much better performance than direct interpretation of source code.
(my emphasis)
And as others have mentioned possible weak obfuscation of the source code.

- 62,498
- 72
- 186
- 247
-
Thank you for answering my question. I really appreciate that. If we are using a bytecode we need JDK. JDK's are heavy and nodes are short on resources. Installing full-fledged JDK on the network nodes is not a good idea. On the other hand,passing the source code to every just needs a compiler. HELP ME AGAIN – Dec 15 '14 at 17:22
-
@RahulMathur: if you are talking about distributing bytecode to run on client computers then you don't need the JDK, you only need the JRE. See: http://stackoverflow.com/questions/1906445/what-is-the-difference-between-jdk-and-jre – User Dec 16 '14 at 02:53
The main reason for the compilation is that the Virtual Machines which are used to host java classes and run them only understands bytecode And since compiling a class each time to the language the virtual machine understands is expensive. That's the only reason why the source code is compiled into bytecode. But we can also use some compilers which compiles source code directly into machine code.But that's a different story which I don't know about much.

- 960
- 12
- 15