Vaibhav G Garg wrote:I have few queries regarding compiling v/s execution of a java program. Suppose I have a Main Class which is referring to class Test which is present in JarA. Now, at compile time, this jar JarA must be present in classpath/buildpath. So, what actually is the action performed by the compiler by referring to this jar?
Well, the compiler does
two things:
1. It ensures that your class is syntactically (ie, "grammatically") correct.
2. It converts your source (
.java) code to byte (
.class) code.
So, if your
Main class calls a method in
Test, it will ensure that you called it correctly. And in order to do that it needs to be able to see the contents of
Test, which at this stage can be either a
.java or a
.class file.
Now, at runtime also, this jar should be present to execute the Main class. Is this correct? If yes, then what is the action performed by JRE when it refers to this class at runtime? WOn't all the dependencies be resolved at compile time only?
No, The
java command works exclusively with jars and
.class files (jars are simply a way of holding multiple classes, in packages, in a single file), but it still needs (among
many other things) to ensure that when your Main class actually calls the Test method, that everything is OK to go. If not, the
JVM is responsible for throwing whatever Exception is necessary to indicate an
execution error.
Example:
take the following code snippet:
File file = new File("myPoem.txt");
FileInputStream fis = new FileInputStream(file);
The compiler can make sure:
1. That there are classes called
File and
FileInputStream.
2. That
File has a constructor that takes a
String.
3. That
FileInputStream has a constructor that takes a
File.
What it
cannot do is know whether:
a. There is a file called "myPoem.txt" available.
b. Whether you are allowed to read it.
(Don't forget that while you compile once, you might deploy the
result to 50 different machines).
HIH
Winston