1

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 ?

5
  • 5
    Because compiling bytecode takes less time than compiling source code? Because bytecode is smaller than source code? Commented Dec 13, 2014 at 7:12
  • Yeah, that's about the size of it. Good question, though. Commented Dec 13, 2014 at 7:15
  • Also because byte code isn't as easily viewable / modified by the end user. Commented Dec 13, 2014 at 7:15
  • 1
    Because the compiler is too big? Because developers don't want to open-source? Commented Dec 13, 2014 at 7:15
  • Even Javascript is usually compiled to Javascript before being sent to the browser ;-) Commented Dec 13, 2014 at 7:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
@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: stackoverflow.com/questions/1906445/…
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.