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– John Dvorak2014-12-13 07:12:50 +00:00Commented Dec 13, 2014 at 7:12
-
Yeah, that's about the size of it. Good question, though.Jon Kiparsky– Jon Kiparsky2014-12-13 07:15:31 +00:00Commented Dec 13, 2014 at 7:15
-
Also because byte code isn't as easily viewable / modified by the end user.Jonathon Reinhart– Jonathon Reinhart2014-12-13 07:15:36 +00:00Commented Dec 13, 2014 at 7:15
-
1Because the compiler is too big? Because developers don't want to open-source?user4098326– user40983262014-12-13 07:15:57 +00:00Commented Dec 13, 2014 at 7:15
-
Even Javascript is usually compiled to Javascript before being sent to the browser ;-)John Dvorak– John Dvorak2014-12-13 07:17:21 +00:00Commented Dec 13, 2014 at 7: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.
2 Comments
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.